多个命令行参数
Multiple command line arguments
我研究了一些 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
模块和 post 示例来做到这一点,那将非常有用!
忘记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
,或不接受任何参数。
现在如果我们添加 'cite' 和 'arbitrary' 选项,这应该给我们:
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 并且发现了用于解析命令行参数的 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
模块和 post 示例来做到这一点,那将非常有用!
忘记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
,或不接受任何参数。
现在如果我们添加 'cite' 和 'arbitrary' 选项,这应该给我们:
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在代码中使用它之前。
救命稻草!