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?

  1. A.

    os.path

  2. B.

    sys.argv

  3. C.

    input.argv

  4. D.

    args.sys

  5. 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 42 gives sys.argv == ['app.py', 'hello', '42'] (every element is a string).

Why the others do not fit

  • os.path is 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, and command.line are not real Python objects at all; input is 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.

Explore the full course: Ibps So It Mains

Loading lesson…