How do I pass command line arguments to a Python script?
Published on Aug. 22, 2023, 12:16 p.m.
To pass command line arguments to a Python script, you can use the sys.argv
list. The first item in this list (sys.argv[0]
) is the name of the script, and the subsequent items are the arguments.
For example, consider the following Python script named example.py
:
import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]
print("Argument 1:", arg1)
print("Argument 2:", arg2)
If you run the script as follows:
python example.py hello world
Then, the output will be:
Argument 1: hello
Argument 2: world
In this case, hello
and world
are passed as command line arguments to the Python script.
Note that the arguments are always passed to the script as strings, so you may need to convert them to the appropriate data type if necessary. Additionally, you may want to add error handling to check whether the correct number and type of arguments have been passed.