Argparse Tutorial — Introducing Positional arguments

import argparse parser = argparse.ArgumentParser() parser.add_argument("echo") args = parser.parse_args() print(args.echo)

Bounded code example (external data; do not execute automatically):
```shell-session
$ 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

options:
-h, --help show this help message and exit
$ python prog.py foo
foo
```

We've added the ~ArgumentParser.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 ~ArgumentParser.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)

Bounded code example (external data; do not execute automatically):
```shell-session
$ python prog.py -h
usage: prog.py [-h] echo

positional arguments:
echo echo the string you use here

options:
-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.square2)

Following is a result of running the code

Bounded code example (external data; do not execute automatically):
```shell-session
$ python prog.py 4
Traceback (most recent call last):
File "prog.py", line 5, in <module>
print(args.square**2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
``` …