How do I access command line arguments? How do I access command line arguments? python python

How do I access command line arguments?


Python tutorial explains it:

import sysprint(sys.argv)

More specifically, if you run python example.py one two three:

>>> import sys>>> print(sys.argv)['example.py', 'one', 'two', 'three']


To get only the command line arguments

(not including the name of the Python file)

import syssys.argv[1:]

The [1:] is a slice starting from the second element (index 1) and going to the end of the arguments list. This is because the first element is the name of the Python file, and we want to remove that.


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 argparseparser = 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] counterpositional 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


matomo