python之argparse

python标准库模块argparse用于解析命令行参数,编写用户友好的命令行界面,该模块还会自动生成帮助信息,并在所给参数无效时报错。
实例用法:

import argparse
desc = 'Process some integers'
parser = argparse.ArgumentParser(description=desc)
#创建一个解析处理器
parser.add_argument('integers',metavar='N',type=int,nargs='+',help='an integer for the accumulator')
"""
add_argument方法:
1、positional arguments
定位参数,不用带-就可以用,默认必选,如上例'integers'
2、optional arguments
-shortname
--fullname
3、action='store_true'、action='sore_const'
4、type
5、choice
6...
"""
parser.add_argument('--sum',dest='accumulate',action='store_const',const=sum,default=max,help='sum the intergers')
args = parser.parse_args()
print(args.accumulate(args.integers))

参考:

https://www.cnblogs.com/yymn/p/8056487.html
https://docs.python.org/3.4/howto/argparse.html#id1

猜你喜欢

转载自blog.csdn.net/qq_38213612/article/details/80189138
今日推荐