Command Line Arguments in Python
In Python, command line arguments are values passed to a script when running it from the terminal or command prompt. They act like inputs, allowing you to change a program’s behavior without modifying the code.
Example:
python add.py 10 20
Here:
python:runs the interpreteradd.py:script name10 20:arguments passed to the program
Ways to Handle Command Line Arguments
Python provides the following built-in modules to handle command-line arguments:
- sys module: gives access to arguments as a list (sys.argv).
- getopt module: helps parse arguments similar to how options work in Unix/Linux commands.
- argparse module: the most powerful and user-friendly way to define, parse, and handle arguments.
1. Using sys.argv
The simplest way to access command line arguments in Python is through the sys module. It provides a list called sys.argv that stores everything you type after python in the command line.
- sys.argv: A list in Python that contains all the command-line arguments.
- sys.argv[0]: Always holds the name of the script being executed (e.g., add.py).
- sys.argv[1:]: Holds the actual arguments you pass (e.g., numbers like 10 20, file names, or other inputs).
import sys
print("Total arguments:", len(sys.argv))
print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
total = 0
for arg in sys.argv[1:]:
total += int(arg)
print("Sum =", total)
Run
python add.py 5 10 15
Output
Total arguments: 4
Script name: add.py
Arguments: ['5', '10', '15']
Sum = 30
Explanation:
- sys.argv[0]: script name (e.g., add.py).
- sys.argv[1:]: user-provided arguments (e.g., numbers).
- len(sys.argv): gives total count of arguments.
- A loop converts arguments to integers and sums them.
2. Using getopt
getopt module is used when you want to handle flags and options (both short -h and long --help styles). It is helpful when your script needs command-line options similar to Linux commands.
Example:
import getopt, sys
args = sys.argv[1:]
options = "hmo:"
long_options = ["Help", "My_file", "Output="]
try:
arguments, values = getopt.getopt(args, options, long_options)
for currentArg, currentVal in arguments:
if currentArg in ("-h", "--Help"):
print("Showing Help")
elif currentArg in ("-m", "--My_file"):
print("File name:", sys.argv[0])
elif currentArg in ("-o", "--Output"):
print("Output mode:", currentVal)
except getopt.error as err:
print(str(err))
Run
python script.py -o result.txt
Output
Output mode: result.txt
Explanation:
- sys.argv[1:]: gets arguments passed to the script.
- options = "hmo:": short options: -h, -m, -o (-o expects a value).
- long_options: long versions: --Help, --My_file, --Output=<val>.
- getopt.getopt(): parses arguments into (option, value) pairs.
Loop:
- -h / --Help: prints help.
- -m / --My_file: prints script name.
- -o / --Output: prints the provided value.
- Error handling: catches invalid options.
3. Using argparse
argparse is the easiest and most powerful way to handle command-line arguments in Python. It has the following features:
- Automatically creates help messages.
- Supports default values, type checking, and options.
- Comes with a built-in -h / --help flag.
Example 1: Basic Parser
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
Run
python script.py -h
Output
usage: script.py [-h]
optional arguments:
-h, --help show this help message and exit
Explanation:
- argparse.ArgumentParser(): creates a parser object to handle arguments.
- parser.parse_args(): processes the arguments from the command line.
- Since no arguments are defined, the script only supports the default -h/--help option.
Example 2: Adding Description
import argparse
parser = argparse.ArgumentParser(description="Demo of argparse")
parser.parse_args()
Run
python script.py -h
Output
usage: script.py [-h]
Demo of argparse
options:
-h, --help show this help message and exit
Explanation:
- argparse module: used to handle command-line arguments in Python.
- ArgumentParser(description=...): creates a parser object. The description is shown when you use the help option.
- parse_args(): processes the arguments given when running the script.
Example 3: Optional Argument
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--Output", help="Show output message")
args = parser.parse_args()
if args.Output:
print("Output:", args.Output)
Run
python script.py -o Hello
Output
Output: Hello
Explanation:
- add_argument("-o", "--Output", ...): defines an optional argument with short form -o and long form --Output.
- help="...": shows a helpful description in the usage message.
- args.Output: stores the value passed with the -o/--Output flag.
- If provided, the script prints it.