【发布时间】:2015-11-30 22:46:34
【问题描述】:
我一直在研究一点 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已弃用;改用更通用的argparsemodule。它支持每个选项的多个值。 -
相关阅读 - PEP 0389 其中提到了deprecation of
optparse和de-emphasizedgetopt -
使用
argparse并用双引号将参数括起来-b "argument with spaces" -
@MartijnPieters 啊啊啊,我不知道!有时我忘记了我正在阅读几年前写的“潜入 Python”......也许如果你把你的评论变成一个答案,我会接受它作为主要答案:)
-
@MatGomes 为什么不将
-b分成两个参数?
标签: python command-line command-line-arguments