$ ls cpython devguide prog.py pypy rm-unused-function.patch $ ls pypy ctypes_configure demo dotviewer include lib_pypy lib-python ... $ ls -l total 20 drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide -rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy -rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch $ ls --help Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. ...
import argparse parser = argparse.ArgumentParser() parser.add_argument("echo", help="echo the string you use here") args = parser.parse_args() print(args.echo)
运行:
1 2 3 4 5 6 7 8
$ 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
现在,在做一些更有意义的事:
1 2 3 4 5
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)
运行结果:
1 2 3 4 5
$ 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'
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)