Python Command Line Arguments: sys.argv and argparse
Learn to read Python command line arguments with sys.argv and argparse. Covers basic usage, named flags, type conversion, and practical script patterns.
Command line arguments pass values into a Python script at runtime, replacing input() prompts with shell-level control.
A script run as python greet.py Alice 30 receives 'Alice' and '30' before it executes a single line of logic, with no blocking prompts and no hardcoded values. That runtime flexibility is the standard pattern for automation scripts, batch jobs, and any tool you want to call from a shell loop without stopping for input.
Python has two built-in approaches: the sys module for direct list access, and argparse for structured option parsing. Both are in the standard library. There is also a third option, getopt, but it predates argparse and is rarely used in new code. This guide covers the two you will actually use.
What Are Command Line Arguments?
When you run a Python script from the terminal, anything typed after the script name is a command line argument. The shell splits the line on spaces and hands each piece to Python as a string. No ceremony.
python script.py hello 42 --verbose
Python stores all of this in sys.argv, a list of strings. The list always contains at least one element: the script name itself. So sys.argv[0] is 'script.py' even when you pass nothing else after it.
The key difference between command line arguments and input() is timing. input() pauses execution mid-run and waits for the user to type something. Command line arguments are already present when the script starts. For scripts run repeatedly in a batch job or a CI pipeline, that is an important distinction: one command, no interactive pauses, results immediately.
Placement coding tests rarely test command line arguments directly. The pattern shows up once you move into tool-building tasks, system design, or project work, where interviewers expect scripts that behave like real programs rather than interactive quizzes.
Reading Arguments with sys.argv
sys.argv is part of the Python sys module, included in every Python installation. Import the module, then index or slice the list as needed.
import sys
print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
print("Count:", len(sys.argv) - 1)
Running python demo.py Alice 30 produces:
Script name: demo.py
Arguments: ['Alice', '30']
Count: 2
Three rules that apply every time you use sys.argv:
sys.argv[0]is always the script name, not user input.sys.argv[1]is the first argument you passed,sys.argv[2]the second, and so on.- All values arrive as strings, including numbers. Running
python demo.py 30makessys.argv[1]equal to'30', not the integer30. Convert withint()orfloat()before arithmetic.
Slicing with sys.argv[1:] is the common shorthand to get just the user-provided arguments, dropping the script name from the front of the list.
Checking Argument Count
Before indexing, check how many arguments arrived to prevent an IndexError at runtime.
import sys
if len(sys.argv) != 3:
print(f"Usage: python {sys.argv[0]} <name> <age>")
sys.exit(1)
name = sys.argv[1]
age = int(sys.argv[2])
print(f"Hello {name}, you are {age} years old.")
This pattern covers the essentials: check the count, print a usage message if it is wrong, and exit with code 1 to signal failure to the calling shell. Any automation layer that wraps this script can check the exit code and act accordingly.
Parsing Named Options with argparse
sys.argv is fine for one or two positional arguments, but becomes manual and error-prone once you need named flags, optional inputs, or type validation. That is what the argparse module is built for.
Here is the same idea as the greatest of three numbers program, rewritten as a proper command line tool using argparse:
import argparse
parser = argparse.ArgumentParser(description="Find the greatest of three numbers.")
parser.add_argument("--a", type=float, required=True, help="First number")
parser.add_argument("--b", type=float, required=True, help="Second number")
parser.add_argument("--c", type=float, required=True, help="Third number")
args = parser.parse_args()
print(f"Greatest: {max(args.a, args.b, args.c)}")
Running python greatest.py --a 5 --b 12 --c 8 outputs Greatest: 12.0.
What argparse handles automatically, without any extra code from you:
- Type conversion.
type=floatmeansargs.ais already afloat. No manualfloat()call after parsing. - Help text. Running
python greatest.py --helpprints a complete usage message generated from eachadd_argumentcall. - Missing required arguments. If
--ais omitted,argparseprints a clear error message and exits before your logic runs. - Default values.
parser.add_argument("--verbose", action="store_true", default=False)givesargs.verboseasFalseunless--verboseis passed on the command line.
Positional vs Optional Arguments
argparse supports two argument styles that you can mix in a single parser.
| Style | Example syntax | Required by default |
|---|---|---|
| Positional | parser.add_argument("filename") | Yes |
| Optional (flag) | parser.add_argument("--output") | No |
Positional arguments are matched by order. Optional arguments are matched by the -- prefix name. A common pattern: a required filename as a positional argument, followed by an optional --output flag for the destination.
sys.argv vs argparse: When to Use Each
| Feature | sys.argv | argparse |
|---|---|---|
| Setup overhead | None | 4 to 5 lines |
Named flags like --name | Manual string parsing | Built-in |
| Type conversion | Manual int(), float() | type= parameter |
| Help text | Write it yourself | Auto-generated |
| Default values | Hardcode them | default= parameter |
| Best for | 1 to 2 positional inputs | Multiple or named options |
The practical rule: sys.argv is enough for a quick positional script you will run yourself. Once the script needs named flags, will be shared with others, or needs to validate types before running, switch to argparse.
For placement project submissions or a public GitHub portfolio, argparse is the professional choice. A reviewer who runs --help and gets a clear usage message is a reviewer who immediately understands your tool without reading the source.
Practical Patterns Worth Knowing
Extending Programs You Already Know
The calculator program in Python uses input() for each operand and operator. Replacing those calls with argparse arguments converts it into a command you can call as python calc.py --a 10 --b 5 --op multiply, usable in shell scripts without any interactive prompts.
The same type-conversion logic applies. Where the input() version calls float(input("Enter number: ")), the argparse version uses parser.add_argument("--a", type=float) and the conversion happens automatically at parse time.
Validating String Arguments
For scripts that accept a single character as input, like the character classification program, argparse lets you add a validation function as the type= argument:
import argparse
def single_char(value):
if len(value) != 1:
raise argparse.ArgumentTypeError("Argument must be exactly one character.")
return value
parser = argparse.ArgumentParser()
parser.add_argument("--char", type=single_char, required=True, help="Character to classify")
args = parser.parse_args()
If the user passes a string longer than one character, argparse catches it before your classification logic ever runs and prints the error message from ArgumentTypeError.
Reading Multiple Values
sys.argv[1:] handles an open-ended list of values cleanly:
import sys
if len(sys.argv) < 2:
print(f"Usage: python {sys.argv[0]} num1 num2 ...")
sys.exit(1)
numbers = [int(x) for x in sys.argv[1:]]
print("Sum:", sum(numbers))
Running python sum.py 4 8 15 16 23 42 gives Sum: 108.
For this pattern, sys.argv is actually simpler than argparse because argparse handles variable-length positional arguments through nargs='+', which adds a line of setup. When the interface is just “give me a list of numbers”, sys.argv[1:] is the direct choice.
If you are building Python fundamentals alongside these patterns, Python basic programs covers the loops, conditions, and functions that every command line tool is assembled from.
Once the argparse skeleton is in place, the distance between python summarise.py --text "some article" and a working LLM command line tool is shorter than most students expect. TinkerLLM (₹299) is where that gap closes. The labs work through the same pattern: calling real language model APIs, parsing the response, and returning structured output.
Primary sources
Frequently asked questions
What is sys.argv[0] in Python?
sys.argv[0] is always the script name. The actual arguments you pass start at sys.argv[1], sys.argv[2], and so on.
How do I pass multiple arguments from the command line in Python?
Separate values with spaces: python script.py arg1 arg2. Each value becomes a separate string element in sys.argv, in the order you typed them.
What is the difference between sys.argv and argparse?
sys.argv gives you a raw list of strings with no structure. argparse parses that list into named options with types, defaults, and help text built in.
Does argparse handle --help automatically?
Yes. argparse builds a help message from your add_argument calls and makes it available via --help with no extra code on your part.
What type does sys.argv return for each argument?
Every element in sys.argv is a string, including numbers. Use int() or float() to convert before doing arithmetic with the value.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)