【发布时间】:2016-07-18 15:14:48
【问题描述】:
我正在使用 getops 进行 args 管理,但由于某种原因,我的 -s 变量不起作用。我的代码如下,以及我得到的输出
try:
opts, args = getopt.getopt(sys.argv[1:], "hadsp:v", ["help", "all", "display", "single=", "present="])#, "search="])
except getopt.GetoptError as err:
print(err)
print "Exiting now, no options entered"
help()
sys.exit(2)
if len(opts) == 0:
print "No options passed"
help()
print opts
print args
for o, a in opts:
if o in ("-h", "--help"):
help()
elif o in ("-p", "--present"):
search(a)
elif o in ("-a", "--all"):
all_install()
elif o in ("-s", "--single"):
if a == '':
print "crap"
sys.exit(2)
single_install(a)
elif o in ("-d", "--display"):
display()
else:
print "Exiting now, unknown option"
help()
sys.exit(2)
输出是
[('-s', '')]
['test']
crap
当我运行程序时:
python file.py -s test
不知道为什么会这样,感谢您的帮助
【问题讨论】:
-
argparse 使用起来更简单安全,
-
第 2 行末尾有一些杂乱无章的东西,包括一个额外的括号和方括号。奇怪的是口译员不抱怨。
-
我认为您想使用参数
hads:p:v而不是hadsp:v。s后面的冒号表示此开关接受一个参数。 -
@JuanTomas,第 2 行有一个
#。最后是评论