在Python中,我们如何找到为脚本提供的命令行参数,并处理它们?
有关更具体的示例,请参见实现“[命令][动作][参数]”风格的命令行界面?以及如何使用Python的optparse格式化位置参数帮助?
在Python中,我们如何找到为脚本提供的命令行参数,并处理它们?
有关更具体的示例,请参见实现“[命令][动作][参数]”风格的命令行界面?以及如何使用Python的optparse格式化位置参数帮助?
当前回答
只是四处宣传argparse,因为这些原因它更好。从本质上讲:
(从链接复制)
argparse module can handle positional and optional arguments, while optparse can handle only optional arguments argparse isn’t dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments. argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance argparse supports parsers that dispatch to sub-commands, while optparse requires setting allow_interspersed_args and doing the parser dispatch manually
我个人最喜欢的是:
Argparse允许类型和 add_argument()的操作参数 用simple指定 调用对象,而optparse需要 破解类属性,比如 获取STORE_ACTIONS或CHECK_METHODS 正确的参数检查
其他回答
Pocoo的点击更直观,需要的样板文件更少,而且至少和argparse一样强大。
到目前为止,我遇到的唯一缺点是您不能对帮助页面进行很多自定义,但这通常不是必需的,而docopt似乎是明确的选择。
我的解是入口点2。例子:
from entrypoint2 import entrypoint
@entrypoint
def add(file, quiet=True):
''' This function writes report.
:param file: write report to FILE
:param quiet: don't print status messages to stdout
'''
print file,quiet
帮助文本:
usage: report.py [-h] [-q] [--debug] file
This function writes report.
positional arguments:
file write report to FILE
optional arguments:
-h, --help show this help message and exit
-q, --quiet don't print status messages to stdout
--debug set logging level to DEBUG
同样在python3中,你可能会发现使用Extended Iterable Unpacking来处理可选的位置参数很方便,没有额外的依赖关系:
try:
_, arg1, arg2, arg3, *_ = sys.argv + [None] * 2
except ValueError:
print("Not enough arguments", file=sys.stderr) # unhandled exception traceback is meaningful enough also
exit(-1)
上面的argv解包使arg2和arg3成为“可选的”——如果在argv中没有指定它们,它们将是None,而如果没有指定第一个,ValueError将被解析:
Traceback (most recent call last):
File "test.py", line 3, in <module>
_, arg1, arg2, arg3, *_ = sys.argv + [None] * 2
ValueError: not enough values to unpack (expected at least 4, got 3)
它处理简单的开关,带有可选替代标志的值开关。
import sys
# [IN] argv - array of args
# [IN] switch - switch to seek
# [IN] val - expecting value
# [IN] alt - switch alternative
# returns value or True if val not expected
def parse_cmd(argv,switch,val=None,alt=None):
for idx, x in enumerate(argv):
if x == switch or x == alt:
if val:
if len(argv) > (idx+1):
if not argv[idx+1].startswith('-'):
return argv[idx+1]
else:
return True
//expecting a value for -i
i = parse_cmd(sys.argv[1:],"-i", True, "--input")
//no value needed for -p
p = parse_cmd(sys.argv[1:],"-p")
还有argparse stdlib模块(对stdlib的optparse模块的“改进”)。示例来自argparse的介绍:
# script.py
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'integers', metavar='int', type=int, choices=range(10),
nargs='+', help='an integer in the range 0..9')
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))
用法:
$ script.py 1 2 3 4
4
$ script.py --sum 1 2 3 4
10