How do I access command line arguments?
Categories:
Accessing Command Line Arguments in Python

Learn how to retrieve and parse command-line arguments in Python scripts using the sys
and argparse
modules for robust application development.
When you run a Python script from the command line, you often need to pass information to it. These pieces of information are known as command-line arguments. They allow your script to be more flexible and dynamic, performing different actions or processing different data based on the input provided at runtime. This article will guide you through the primary methods for accessing and handling these arguments in Python.
Basic Access with sys.argv
The most straightforward way to access command-line arguments in Python is by using the sys
module, specifically the sys.argv
list. This list contains all the command-line arguments, where sys.argv[0]
is the script name itself, and subsequent elements (sys.argv[1]
, sys.argv[2]
, etc.) are the arguments passed to the script.
import sys
print(f"Number of arguments: {len(sys.argv)}")
print(f"Argument List: {sys.argv}")
if len(sys.argv) > 1:
print(f"First argument: {sys.argv[1]}")
print(f"All arguments after script name: {sys.argv[1:]}")
else:
print("No arguments provided after the script name.")
A simple Python script to print all command-line arguments.
To run this script, save it as my_script.py
and execute it from your terminal:
python my_script.py hello world 123
Example command-line execution.
The output would be:
Number of arguments: 4
Argument List: ['my_script.py', 'hello', 'world', '123']
First argument: hello
All arguments after script name: ['hello', 'world', '123']
Output from the example script.
sys.argv
elements are always strings. If you expect numerical input, you'll need to explicitly convert them (e.g., int(sys.argv[1])
).Advanced Argument Parsing with argparse
While sys.argv
is useful for simple cases, it quickly becomes cumbersome for scripts that require multiple arguments, optional arguments, flags, or help messages. For more robust and user-friendly command-line interfaces, Python's built-in argparse
module is the standard solution. It handles parsing, type conversion, and generates help and usage messages automatically.
flowchart TD A[Start Script] --> B{Define Parser} B --> C[Add Arguments (positional, optional)] C --> D[Parse Arguments] D --> E{Access Arguments} E --> F[Perform Actions]
Workflow for parsing command-line arguments using argparse
.
Here's how to use argparse
:
import argparse
# 1. Create the parser
parser = argparse.ArgumentParser(description='A simple script that greets a user and performs an operation.')
# 2. Add arguments
parser.add_argument('name', type=str, help='The name of the user to greet.')
parser.add_argument('--age', type=int, default=30, help='An optional age for the user.')
parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output.')
# 3. Parse the arguments
args = parser.parse_args()
# 4. Access and use the arguments
print(f"Hello, {args.name}!")
print(f"You are {args.age} years old.")
if args.verbose:
print("Verbose mode is enabled.")
else:
print("Verbose mode is disabled.")
Using argparse
for a more structured command-line interface.
Save this as greet_script.py
and try running it with different arguments:
# Basic usage
python greet_script.py Alice
# With optional arguments
python greet_script.py Bob --age 25 -v
# Accessing help message
python greet_script.py --help
Examples of running the argparse
script.
The argparse
module automatically generates a helpful message when you use --help
or -h
:
usage: greet_script.py [-h] [--age AGE] [-v]
A simple script that greets a user and performs an operation.
positional arguments:
name The name of the user to greet.
options:
-h, --help show this help message and exit
--age AGE An optional age for the user.
-v, --verbose Enable verbose output.
Automatically generated help message by argparse
.
argparse
module supports many features, including subcommands, mutually exclusive groups, and custom actions. Refer to the official Python documentation for advanced usage.Choosing the Right Tool
The choice between sys.argv
and argparse
depends on the complexity of your script's command-line interface:
sys.argv
: Best for very simple scripts that take one or two positional arguments, or when you need direct access to the raw argument list without any parsing overhead.argparse
: Essential for any script that requires multiple arguments, optional flags, type validation, default values, or a user-friendly help message. It makes your scripts more robust, maintainable, and easier for others to use.
For most practical applications, especially those intended for distribution or frequent use, argparse
is the recommended approach due to its comprehensive features and ease of use for both developers and end-users.