ArgumentParser
Now let us look at argparse
in more detail.
Firstly, let us look at the argparse.ArgumentParser
object, which was the first thing we constructed.
I want you to look at the documentation. Explore the parameters available. It’s ok if some of them do not make sense at the moment. Some might make more sense later. You might not use most of these anyway. We have used description
in our earlier example. But perhaps we can try to also add an “ending message”? And perhaps change the “usage” description in the first line?
Your task: Try to produce the following help for our calculator program:
$ python3 calculator.py -h
usage: Type in python3 calculator.py x y operation
Best calculator in the world, period.
positional arguments:
x
y
{add,sub,mul,div}
optional arguments:
-h, --help show this help message and exit
That is all I have to say!
Loaidng command line arguments from a file
It is also worth highlighting the fromfile_prefix_chars
keyword argument, which allows you to load your arguments from a file. Useful for when you have a long list of parameters.
Say that I created a new file called list_of_args.txt
with the following content:
5
3
add
In the example below (say supercalculator.py
), I tell argparse
to load the command line arguments from the file if it sees a command line argument that starts with a @
import argparse
parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
parser.add_argument("x", type=int)
parser.add_argument("y", type=int)
parser.add_argument("operation", choices=['add', 'sub', 'mul', 'div'])
args = parser.parse_args()
print(args)
When you run the program, argparse
will load the arguments directly from list_of_args.txt
$ python3 supercalculator.py @list_of_args.txt
Namespace(operation='add', x=5, y=3)