Command-line argument

A value passed to a program on the command line when you run it, read in Python from sys.argv.

When you start a program with something like python greet.py Ada, everything after the script name is a command-line argument. Python collects them in sys.argv, a list of strings: sys.argv[0] is the script's own name, and your arguments start at index 1. They let one script work on any file or value instead of a hard-coded one.

Example
import sys

# Run as:  python greet.py Ada
print(sys.argv)        # ["greet.py", "Ada"]
print(sys.argv[1])     # "Ada"  — arguments start at index 1
Output
$ python greet.py Ada
['greet.py', 'Ada']
Ada

Where this shows up in real Python

Command-line arguments let one script behave differently each run — pass it a filename or an option instead of editing the code.

Commonly used Command-line argument tools

  • import sys — sys.argv holds the raw arguments
  • sys.argv[1:] — everything after the script name
  • argparse — the standard way to define real flags and help

Official documentation: Python Library Reference: sys.argv

Related lessons

Related terms