社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python argparse处理命令行参数

生信修炼手册 • 5 年前 • 563 次点击  
欢迎关注”生信修炼手册”!
对于脚本编程而言,经常需要从命令行传递参数到脚本中。对于命令行参数的定义和使用,有一套完整的规则,以linux上的ls命令为例
ls --helpUsage: ls [OPTION]... [FILE]...List information about the FILEs (the current directory by default).Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
Mandatory arguments to long options are mandatory for short options too. -a, --all do not ignore entries starting with . -l use a long listing format -t sort by modification time, newest first

上述命令通过help选项来查看ls命令的帮助文档,输出的内容很多,这里我只截取了部分。从输出的内容可以看到,命令行参数可以分为两大类

  1. 可选参数

  2. 位置参数

option表示可选参数,有两种写法,一种是一个短横杠后面加选项名称,称之为短选项,另外一种是两个短横杠后面加选项名称,称之长选项。位置参数是必须提供的,前面不需要短横杠的修饰,直接就是参数名称,ls命令的用法示意如下

ls -l dir

其中-l就是一个选项, dir则是一个位置参数, 要在python脚本中实现这样的命令行传参,可以借助内置模块argparse来实现,基本用法示意如下

import subprocessimport argparseimport shlex# 定义一个命令行参数解析器parser = argparse.ArgumentParser()# 添加选项parser.add_argument('-l', '--long', dest = 'long', action = 'store_true', help = 'use long list format')# 添加位置参数parser.add_argument('dir',  help = 'direatory name')# 捕获选项和参数args = parser.parse_args()#通过属性访问各个参数cmd = 'ls {}'.format(args.dir)
if args.long: cmd = 'ls -l {}'.format(args.dir)
print(shlex.split(cmd))subprocess.run(shlex.split(cmd))

在命令行运行该脚本

python test.pyusage: test.py [-h] [-l] dirtest.py: error: the following arguments are required: dir

可以看到,argparse为脚本自动添加了-h选项,用来查看帮助文档

python test.py -husage: test.py [-h] [-l] dir
positional arguments: dir direatory name
optional arguments: -h, --help show this help message and exit -l, --long use long list format

argparse会格式化输出帮助信息。在该模块中,关键的是掌握add_argument方法的使用,该方法有多个参数,列表如下

1. name
表示参数的名称,选项可以同时提供短选项和长选项,也可以只提供其中的一种,位置参数直接写参数名称即可, 用法如下
# 指定一个短选项>>> parser.add_argument('-l')_StoreAction(option_strings=['-l'], dest='l', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)


    
# 指定一个常选项>>> parser.add_argument('--long')_StoreAction(option_strings=['--long'], dest='long', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)# 同时指定长选项和短选项>>> parser.add_argument('-p','--threads' )_StoreAction(option_strings=['-p', '--threads'], dest='threads', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)# 指定位置参数>>> parser.add_argument('name' )_StoreAction(option_strings=[], dest='name', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
2. type

命令行传递的参数默认用字符串存储,如果要转换成其他数据类型等,比如整数,浮点数等,可以通过指定type的值来实现,用法如下

# type = int, 转换为整型>>> parser.add_argument('-t','--cpus', type = int)_StoreAction(option_strings=['-t', '--cpus'], dest='cpus', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)# type = float, 转换为浮点型>>> parser.add_argument('-c','--cutoff', type = float)_StoreAction(option_strings=['-c', '--cutoff'], dest='cutoff', nargs=None, const=None, default=None, type=<class 'float'>, choices=None, help=None, metavar=None)#  支持直接读写文件>>> parser.add_argument('file', type = argparse.FileType('r'))_StoreAction(option_strings=[], dest='file', nargs=None, const=None, default=None, type=FileType('r'), choices=None, help=None, metavar=None)

3. default

参数的默认值, 用法如下

>>> parser.add_argument('-t','--threads', type = int, default = 10)_StoreAction(option_strings=['-t', '--threads'], dest='threads', nargs=None, const=None, default=10, type=<class 'int'>, choices=None, help=None, metavar=None)

4.required

通过指定required=True, 可以将可选参数变为必须参数,用法如下

>>> parser.add_argument('-t','--threads', type = int, default = 10, required = True)_StoreAction(option_strings=['-t', '--threads'], dest='threads', nargs=None, const=None, default=10, type=<class 'int'>, choices=None, help=None, metavar=None)

5. help

指定参数的帮助信息,当运行-h时,help的值会显示在屏幕上, 用法如下

>>> parser.add_argument('-t','--threads', type = int, default = 10, help = 'cpu numbers')_StoreAction(option_strings=['-t', '--threads'], dest='threads', nargs=None, const=None, default=10, type=<class 'int'>, choices=None, help='cpu numbers'


    
, metavar=None)

6. dest

参数的名称,默认通过name参数的值来访问参数,当指定了dest参数时,则用dest的值来访问对应的参数,用法如下

>>> parser.add_argument('-t','--threads', dest = 'cpus', type = int, default = 10)_StoreAction(option_strings=['-t', '--threads'], dest='cpus', nargs=None, const=None, default=10, type=<class 'int'>, choices=None, help=None, metavar=None)

7. metavar

参数的别名,当运行-h来查看脚本的帮助信息时,默认使用name或者dest的值,如果指定了metavar,则参数名称显示为metavar的值, 该参数仅在显示帮助信息时有用,没有其他实际含义,用法如下

>>> parser.add_argument('-t', dest = 'cpus', metavar = 'threads', type = int, default = 10)_StoreAction(option_strings=['-t'], dest='cpus', nargs=None, const=None, default=10, type=<class 'int'>, choices=None, help=None, metavar='threads')

8. choices

其值为一个列表,指定了参数的可选范围,如果提供的值超出范围,程序会报错, 用法如下

>>> parser.add_argument('-t','--threads', choices = range(21), type = int, default = 10)_StoreAction(option_strings=['-t', '--threads'], dest='threads', nargs=None, const=None, default=10, type='int'>, choices=range(0, 21), help=None, metavar=None)

9. action

指定参数的行为,默认值为store, 只存储对应的值,还有其他的可选值,用法如下

# 默认action = store>>> parser.add_argument('name' )_StoreAction(option_strings=[], dest='name', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)# 指定该参数时,其值为True>>> parser.add_argument('--quiet', action = 'store_true')_StoreTrueAction(option_strings=['--quiet'], dest='quiet', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)# 指定该参数时,其值为False>>> parser.add_argument('--log', action = 'store_false')_StoreFalseAction(option_strings=['--log'], dest='log', nargs=0, const=False, default=True, type=None, choices=None, help=None, metavar=None)# 参数的值为const对应的值>>> parser.add_argument('chrs', action = 'store_const', const = 'chr1')_StoreConstAction(option_strings=[], dest='chrs', nargs=0, const='chr1', default=None, type=None, choices=None, help=None, metavar=None)# 参数的值为一个列表>>> parser.add_argument('chrs', action = 'append')_AppendAction(option_strings=[], dest='chrs', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)# 参数的值为一个列表>>> parser.add_argument('chrs', action = 'extend')


    
_ExtendAction(option_strings=[], dest='chrs', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)

10. const

当action = store_const或者append_const时发挥作用,将参数的值设置为const参数对应的常数,用于固定参数的值,用法如下

>>> parser.add_argument('-t','--threads', action = 'store_const', const = 10)_StoreConstAction(option_strings=['-t', '--threads'], dest='threads', nargs=0, const=10, default=None, type=None, choices=None, help=None, metavar=None)

11. nargs

定义参数值的个数,默认参数都是一个值,指定该参数,则参数的值用列表存储,比如nargs=1, 此时参数为长度为1 的列表,用法如下

# 指定一个具体的数值,对参数的个数进行限定# 提供的参数个数不对,会报错>>> parser.add_argument('names', nargs = 2)_StoreAction(option_strings=[], dest='names', nargs=2, const=None, default=None, type=None, choices=None, help=None, metavar=None)# ?表示参数的值为0个或者多个,用default指定没有提供参数时的默认值>>> parser.add_argument('chrs', nargs = '?', default = 'chr1')_StoreAction(option_strings=[], dest='chrs', nargs='?', const=None, default='chr1', type=None, choices=None, help=None, metavar=None)# *表示参数的值为0个或者多个>>> parser.add_argument('names', nargs = '*')_StoreAction(option_strings=[], dest='names', nargs='*', const=None, default=None, type=None, choices=None, help=None, metavar=None)# 加号表示参数的值为1个或者多个>>> parser.add_argument('samples', nargs = '+')_StoreAction(option_strings=[], dest='samples', nargs='+', const=None, default=None, type=None, choices=None, help=None, metavar=None)

通过多个参数的组合,提供了强大的命令行传参方式,尽管在python中还有其他模块也提供了命令行参数的处理功能,但是官方还是首推使用argparse来处理命令行参数。

·end·

—如果喜欢,快分享给你的朋友们吧—



原创不易,欢迎收藏,点赞,转发!生信知识浩瀚如海,在生信学习的道路上,让我们一起并肩作战!
本公众号深耕耘生信领域多年,具有丰富的数据分析经验,致力于提供真正有价值的数据分析服务,擅长个性化分析,欢迎有需要的老师和同学前来咨询。
  更多精彩



  写在最后


转发本文至朋友圈,后台私信截图即可加入生信交流群,和小伙伴一起学习交流。


扫描下方二维码,关注我们,解锁更多精彩内容!


一个只分享干货的

生信公众号



Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/63016
 
563 次点击