我正在研究本文here,试图解析一些命令行参数,但是我构建的脚本不断删除最后一个参数。
为简单起见,我重现了如下问题:
import getopt
argv = ["-c", "config", "-o", "hello", "-e", "fu bar", "-q", "this is a query"]
opts, args = getopt.getopt(argv, "c:o:e:q", ["cfile=", "ofile=", "entry=", "query="])
for opt, arg in opts:
print(opt, arg)
这是我得到的输出:
-c config
-o hello
-e fu bar
-q
我要去哪里错了?
答案 0 :(得分:6)
冒号(:
)不是分隔符,它需要遵循in the docs所述的每个参数:
shortopts 是脚本要识别的选项字母字符串,其中的选项要求参数后跟一个冒号(
':'
;即,与Unix {{ 1}}使用)。
因此,您应该将getopt()
更改为"c:o:e:q"
您链接到的教程也以相同的方式使用它。