Python枚举删除列表的最后一个元素

ds_*_*ner 3 python python-3.x

我在这里试图解析一些命令行参数,但是我构建的脚本不断删除最后一个参数.

为了保持简单,我重现了这样的问题:

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)
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

-c config
-o hello
-e fu bar
-q
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

Sel*_*cuk 6

冒号(:)不是分隔符,它需要遵循文档中所述的每个参数:

shortopts是脚本想要识别的选项字母串,其中的选项需要一个后跟冒号的参数(':'即,与Unix getopt()使用的格式相同).

因此你应该"c:o:e:q"改为"c:o:e:q:"

您链接的教程也以相同的方式使用它.