🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreePython Read Command Line Arguments With argparse

Passing values to a Python script means supplying them when you start it. Python’s argparse module lets you define those inputs and parse them for use in the program.
I’ll show how to declare a required filename and set defaults for options callers omit.
TL;DR
Use argparse for a script that needs named options, type conversion, defaults and a helpful usage message.
- Read sys.argv directly for a tiny script with a fixed number of values.
- Choose argparse when callers need named options or validation.
- Choose getopt when you need its Unix-style option interface.
What Are Python Command-Line Arguments?
A command-line argument is a value a caller supplies with the command that starts a program, and Python exposes it as a string in sys.argv with the script name or path at index zero.
By contrast, input() waits for a person to type after the program reaches that call.
| Approach | Use it when | What you handle |
|---|---|---|
| sys.argv | A small script has a fixed input order. | Indexes, missing values and conversion. |
| getopt | You need familiar short or long Unix-style options. | Option declarations and the returned option/value pairs. |
| argparse | The interface has named options, defaults or validation. | Argument definitions, while the parser builds help and reports common input errors. |
A positional value is recognized by its place in the command. An optional value has a flag such as --copies, and a switch can turn a setting on or off.
How to Read Python Command-Line Arguments Step by Step
Use argparse to define the file and its named settings before calling parse_args().
Step 1: Declare positional and named inputs
Save this as argument_demo.py. The filename is positional, label has a default, and copies becomes an integer.
import argparse
def build_parser():
parser = argparse.ArgumentParser(
description="Prepare a report for one input file."
)
parser.add_argument("file", help="input file to process")
parser.add_argument("--label", default="unlabeled", help="label for this run")
parser.add_argument(
"--copies",
type=int,
default=1,
help="number of copies to prepare (default: 1)",
)
return parser
def main():
args = build_parser().parse_args()
print(f"File: {args.file}")
print(f"Label: {args.label}")
print(f"Copies: {args.copies}")
if __name__ == "__main__":
main()
Run the file with a filename and label that contain spaces, then pass a count. I ran this command and got the values below.
python3 argument_demo.py "quarterly report.csv" --label "April batch" --copies 2
File: quarterly report.csv
Label: April batch
Copies: 2

Step 2: Let defaults cover omitted options
I ran the command with only its filename, and the terminal printed the three values below.
python3 argument_demo.py "quarterly report.csv"
File: quarterly report.csv
Label: unlabeled
Copies: 1

Common Argument Errors and Edge Cases
Declare required inputs so argparse reports missing values, and quote filenames with spaces so the shell passes each as one argument.
A missing positional value gets a usage error
I left out the required filename. Argparse ended with “the following arguments are required: file,” rather than raising IndexError from a list access.
python3 argument_demo.py --copies 2
usage: argument_demo.py [-h] [--label LABEL] [--copies COPIES] file
argument_demo.py: error: the following arguments are required: file

Quote filenames that contain spaces
I ran the filename without quotes. Argparse accepted quarterly as the file value, then rejected report.csv as an extra argument.
python3 argument_demo.py quarterly report.csv --label "April batch" --copies 2
usage: argument_demo.py [-h] [--label LABEL] [--copies COPIES] file
argument_demo.py: error: unrecognized arguments: report.csv

Quote the full filename in the command so it reaches Python as one value. The earlier successful command shows the spaced filename intact in the output.
Long-option prefixes can be accepted
I shortened --label to --lab and --copies to --cop. The default parser accepted both unique prefixes.
python3 argument_demo.py "quarterly report.csv" --lab "April batch" --cop 3
File: quarterly report.csv
Label: April batch
Copies: 3

Set allow_abbrev=False when callers should use full option names. I tested --cop with that setting and got an unrecognized-arguments error.
import argparse
def build_parser():
parser = argparse.ArgumentParser(
description="Prepare a report for one input file.",
allow_abbrev=False,
)
parser.add_argument("file", help="input file to process")
parser.add_argument("--label", default="unlabeled", help="label for this run")
parser.add_argument(
"--copies",
type=int,
default=1,
help="number of copies to prepare (default: 1)",
)
return parser
def main():
args = build_parser().parse_args()
print(f"File: {args.file}")
print(f"Label: {args.label}")
print(f"Copies: {args.copies}")
if __name__ == "__main__":
main()
python3 strict_argument_demo.py "quarterly report.csv" --label "April batch" --cop 3
usage: strict_argument_demo.py [-h] [--label LABEL] [--copies COPIES] file
strict_argument_demo.py: error: unrecognized arguments: --cop 3

| Symptom | Cause | Response |
|---|---|---|
| IndexError when reading argv | The caller omitted an expected item. | Check the length or declare a required parser argument. |
| A numeric value stays text | Raw argv items are strings. | Convert it or declare type=int in argparse. |
| A spaced filename arrives in parts | The shell split unquoted words before Python started. | Quote the value in the command, as in the example above. |
Conclusion
Start with argparse when a script needs named inputs or useful errors. Keep sys.argv for a small fixed interface you can check by hand.
For the API details, read the official argparse reference, the sys.argv documentation and the getopt reference. AskPython also has focused guides to the Python sys module and parsing arguments with argparse.
FAQ
Quote spaced values in the shell, and use getopt when its Unix-style conventions are required.
Can a Python command-line argument contain spaces?
Yes. Quote the value in the shell command so it reaches Python as one argument. The parser receives the value without the shell’s quote marks.
When should I use getopt instead of argparse?
Use getopt when you need its Unix-style option conventions. For a new interface, Python’s documentation recommends argparse for readers who are not familiar with getopt.


