python中的argparse用法(实例)
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
argparse是Python中的一个常用模块,和sys.argv()功能类似,主要用于编写命令行接口:对于程序所需要的参数,它可以进行正确的解析。另外,argparse还可以自动的生成help和 usage信息,当程序的参数无效时,它可以自动生成错误信息。
具体实例:
一个可以接受多个整数,并返回它们的和或者最大值的python程序。
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
具体实例上述程序保存为,prog.py,在终端进入路径下,对程序进行调用,执行并自动提供有用的help信息:python prog.py -h
对其程序进行有效的输入:
python prog.py 1 2 3 4
python prog.py 1 2 3 4 --sum
If invalid arguments are passed in, it will issue an error:
如果参数传入无效,将会出现错误:
python prog.py a b c
参考https://docs.python.org/3/library/argparse.html