我正在处理这篇文章 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
我哪里错了?
最佳答案
冒号 (:
) 不是分隔符,它需要跟在每个参数后面,如 in the docs 所述:
shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (
':'
; i.e., the same format that Unixgetopt()
uses).
因此您应该将 "c:o:e:q"
更改为 "c:o:e:q:"
您链接到的教程也以相同的方式使用它。
关于Python 枚举删除列表的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54740607/