Python argparse 模块

argparse模块用于从命令行直接读取参数,简单用法如下:

[root@localhost ~]$ vim 1.py
#!/usr/bin/env python
import argparse
                                                                                   
parser = argparse.ArgumentParser(description="xxxxx", usage="xxxxx")               # description="xxxx" :用于描述脚本的用途,可以为空,会在使用 python 1.py -h 查看帮助时显示
parser.add_argument('--verbose', '-v', action='store_true', help='verbose mode')   # usage="xxxxx" :用于描述参数的用法,如果我们使用没有自定义的参数,如 python 1.py -a 则会提示这个信息
args = parser.parse_args()                                                         # --versose/-v :添加可用的参数,表明我们可以使用 python 1.py --verbose 或 python 1.py -v
                                                                                   # action="store_true" :表示当读取的参数中出现 --verbose/-v 时,参数字典的verbose键对应的值为True
if args.verbose:                                                                   # help="verbose mode":用于描述--verbose参数的用途或意义,会在使用 python 1.py -h 查看帮助时显示
    print "Verbose mode on!"
else:
    print "Verbose mode off!"
[root@localhost ~]$ python 1.py       # 如果不加 -v 参数,则 args.verbose 值为 False,返回 "Verbose mode off!"
Verbose mode off!
[root@localhost ~]$ python 1.py -v    # 如果加上 -v 参数,则 args.verbose 值为 True,返回 "Verbose mode on!"
Verbose mode on!
[root@localhost ~]$ python 1.py -h    # -h 参数用于查看帮助信息,该参数不需要定义,默认就有的
usage: 1.py [-h] [--verbose]

your script description

optional arguments:
  -h, --help     show this help message and exit
  --verbose, -v  verbose mode
[root@localhost ~]$ python 1.py -a    # 如果我们使用没有自定义的参数,则会提示 usage="xxxxx" 定义的内容
usage: xxxxx
1.py: error: unrecognized arguments: -a

    

猜你喜欢

转载自www.cnblogs.com/pzk7788/p/10241279.html