Introducing Positional arguments
An example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo
And running the code:
$ python prog.py
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo
$ python prog.py --help
usage: prog.py [-h] echo
positional arguments:
echo
optional arguments:
-h, --help show this help message and exit
$ python prog.py foo
foo
Here is what’s happening:
We’ve added the add_argument() method,
which is what we use to specify which command-line options the program is willing to accept. In this case, I’ve named it echo so
that it’s in line with its function.
Calling our program now requires us to specify an option.
The parse_args() method actually returns
some data from the options specified, in this case, echo.
The variable is some form of ‘magic’ that argparse performs
for free (i.e. no need to specify which variable that value is stored in). You will also notice that its name matches the string argument given to the method, echo.
Note however that, although the help display looks nice and all, it currently is not as helpful as it can be. For example we see that we got echo as
a positional argument, but we don’t know what it does, other than by guessing or by reading the source code. So, let’s make it a bit more useful:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print args.echo
And we get:
$ python prog.py -h
usage: prog.py [-h] echo
positional arguments:
echo echo the string you use here
optional arguments:
-h, --help show this help message and exit
Now, how about doing something even more useful:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number")
args = parser.parse_args()
print args.square**2
Following is a result of running the code:
$ python prog.py 4
Traceback (most recent call last):
File "prog.py", line 5, in
print args.square**2
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
That didn’t go so well. That’s because argparse treats
the options we give it as strings, unless we tell it otherwise. So, let’s tell argparse to
treat that input as an integer:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
type=int)
args = parser.parse_args()
print args.square**2
Following is a result of running the code:
$ python prog.py 4
16
$ python prog.py four
usage: prog.py [-h] square
prog.py: error: argument square: invalid int value: 'four'
That went well. The program now even helpfully quits on bad illegal input before proceeding.