在Python中,我们如何找到为脚本提供的命令行参数,并处理它们?
有关更具体的示例,请参见实现“[命令][动作][参数]”风格的命令行界面?以及如何使用Python的optparse格式化位置参数帮助?
在Python中,我们如何找到为脚本提供的命令行参数,并处理它们?
有关更具体的示例,请参见实现“[命令][动作][参数]”风格的命令行界面?以及如何使用Python的optparse格式化位置参数帮助?
当前回答
同样在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)
其他回答
我喜欢从stdlib中获取getopt,例如:
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err:
usage(err)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
if len(args) != 1:
usage("specify thing...")
最近,我一直在包装类似的东西,使事情更少的啰嗦(例如;使“-h”隐式)。
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))
Assuming the Python code above is saved into a file called prog.py
$ python prog.py -h
Ref-link: https://docs.python.org/3.3/library/argparse.html
我建议使用docopt作为其他选项的简单替代。
Docopt是一个新的项目,它通过解析您的——help使用消息来工作,而不是要求您自己实现所有内容。您只需将您的使用消息放入POSIX格式。
只是四处宣传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 正确的参数检查
我的解是入口点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