我一直在学习一点 Python,并且遇到了用于解析命令行参数的 getopt
模块。
基本上,我有以下代码:
import sys, getopt
print("The list of %s arguments passed:" % len(sys.argv))
# Print each argument
for arg in sys.argv:
print(arg)
print()
# Now print parsed arguments
opts, args = getopt.getopt(sys.argv[1:], "ab:cd", ["arbitrary", "balance=", "cite"])
for opt in opts:
print(opt)
print()
# Print the arguments returned
print(args)
但是,我需要 -b
选项来采用两个不同的参数,例如 -b one Two
。我尝试在 getopt
的参数列表中的 b
后面添加两个冒号,但没有成功。
如果有人可以告诉我如何使用 getopt
模块执行此操作并发布示例,那将非常有用!
最佳答案
忘记 getopt,使用 Docopt (真的):
如果我理解得很好,你希望用户传递 2 个参数来平衡。这可以通过以下方式实现:
doc = """Usage:
test.py balance= <b1> <b2>
test.py
"""
from docopt import docopt
options, arguments = docopt(__doc__) # parse arguments based on docstring above
该程序接受:test.py Balance= X Y
,或不接受任何参数。
现在,如果我们添加“引用”和“任意”选项,这应该给我们:
doc = """
Usage:
test.py balance= <b1> <b2>
test.py
Options:
--cite -c Cite option
--arbitrary -a Arbitrary option
"""
程序现在接受选项。 示例:
test.py balance= 3 4 --cite
=> options = {
"--arbitrary": false,
"--cite": true,
"<b1>": "3",
"<b2>": "4",
"balance=": true
}
提示:此外,您还可以test your documentation string directly in your browser在您的代码中使用它之前。
救星!
关于python - 多个命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32403762/