(continued from previous page) usage: prog.py [-h] prog.py: error: unrecognized arguments: foo Here is what is happening: • Running the script without any options results in nothing displayed to stdout. Not so useful. • The second one starts to display the usefulness of the argparse module. We have done almost nothing, but already we get a nice help message. • The$_{--help}$ option, which can also be shortened to$_{-h}$, is the only option we get for free (i.e. no need to specify it). Specifying anything else results in an error. But even then, we do get a useful usage message, also for free. • 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: Here is what’s happening: And running the code: An example: import argparse parser =argparse.ArgumentParser() parser.add_argument( "echo ") args =parser.parse_args() print(args.echo) $ python3 prog.py usage: prog.py [-h] echo prog.py: error: the following arguments are required: echo $ python3 prog.py --help usage: prog.py [-h] echo positional arguments: echo optional arguments: -h, --help show this help message and exit $ python3 prog.py foo foo import argparse parser =argparse.ArgumentParser() parser.add_argument( "echo ", help="echo the string you use here ") (continues on next page) 3 3 Introducing Positional arguments