In this tutorial, we will explore how to access command line arguments in Python. Command line arguments are values passed to a program when it is executed from the terminal or command prompt. These arguments can be used to customize the behavior of the program, provide input data, or specify configuration options.
Introduction to sys.argv
The sys
module in Python provides a way to access command line arguments through the argv
attribute. sys.argv
returns a list of strings, where each string is an argument passed to the program. The first element of this list, sys.argv[0]
, is always the name of the Python script being executed.
Here’s an example of how to use sys.argv
:
import sys
print(sys.argv)
If we run this script from the terminal like this: $ python example.py one two three
, the output will be:
['example.py', 'one', 'two', 'three']
As you can see, the first element of the list is the name of the Python script, and the remaining elements are the command line arguments.
Accessing Only the Command Line Arguments
If we want to access only the command line arguments, without the name of the Python script, we can use slicing:
import sys
print(sys.argv[1:])
This will output: ['one', 'two', 'three']
.
Using argparse for Robust Argument Parsing
While sys.argv
provides a simple way to access command line arguments, it has some limitations. For example, it doesn’t provide any built-in support for parsing arguments with options (e.g., -h
or --help
). That’s where the argparse
module comes in.
argparse
is a powerful module that allows you to define and parse command line arguments in a robust and flexible way. Here’s an example of how to use argparse
:
import argparse
parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)
In this example, we define an argument named counter
with a help message and a type of int
. When we run the script with an integer argument (e.g., $ python prog.py 1
), it will output: 2
.
Accessing Arguments by Key
With argparse
, you can also access arguments by key using the dest
parameter. Here’s an example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--product_id', dest='product_id', type=str, help='Add product_id')
args = parser.parse_args()
print(args.product_id)
In this example, we define an argument named --product_id
with a destination name of product_id
. When we run the script with this option (e.g., $ python main.py --product_id 1001028
), it will output: 1001028
.
Conclusion
In conclusion, accessing command line arguments in Python can be done using either sys.argv
or argparse
. While sys.argv
provides a simple way to access arguments, argparse
offers more robust and flexible parsing capabilities. By using these modules, you can write Python scripts that are customizable and user-friendly.