Which of the following is used in Python to access command-line arguments…
2024
Which of the following is used in Python to access command-line arguments passed to a program?
- A.
os.path
- B.
sys.argv
- C.
input.argv
- D.
args.sys
- E.
command.line
Attempted by 3 students.
Show answer & explanation
Correct answer: B
Concept
When a Python program is run from a terminal, any words typed after the script name are passed to the program as command-line arguments. Python collects these in a single list provided by the standard sys module. The list is named argv (short for "argument vector"), so the full reference is sys.argv.
Application
To use it, you import the module and read the list:
sys.argv[0]is always the script's own name/path.sys.argv[1],sys.argv[2], ... are the actual arguments the user typed, in order.So running
python app.py hello 42givessys.argv == ['app.py', 'hello', '42'](every element is a string).
Why the others do not fit
os.pathis a submodule for building and inspecting filesystem paths (joining folders, checking extensions) — it has nothing to do with what the user typed on the command line.input.argv,args.sys, andcommand.lineare not real Python objects at all;inputis a built-in for reading interactive keyboard input, and the other two are invented names that do not exist in the language or its standard library.
Hence the standard, correct way to read command-line arguments is sys.argv.