How do I access command line arguments in Python?
Python tutorial explains it:
import sys
print(sys.argv)
More specifically, if you run python example.py one two three
:
>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']
import sys
sys.argv[1:]
will give you a list of arguments (not including the name of the python file)
I highly recommend argparse
which comes with Python 2.7 and later.
The argparse
module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are using sys.argv
approach. And it is for free (built-in).
Here a small example:
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)
and the output for python prog.py -h
usage: simple_example [-h] counter
positional arguments:
counter counter will be increased by 1 and printed.
optional arguments:
-h, --help show this help message and exit
and for python prog.py 1
as you would expect:
2