args =parser.parse_args() print(args.echo) 

And we get: 

$ python3 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: 

(continued from previous page) 

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: 

$ python3 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' 

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: 

$ python3 prog.py 4 16 $ python3 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. 

