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

标签 python python-3.x

我正在处理这篇文章 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 Unix getopt() uses).

因此您应该将 "c:o:e:q" 更改为 "c:o:e:q:"

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

关于Python 枚举删除列表的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54740607/

相关文章:

Python:同时遍历字典中的所有列表以过滤掉元素

python - 执行引用同一列中先前值的计算

python - 使用 groupBy 和过滤器创建新数据框

Python flask saml 抛出 saml2.sigver.SigverError 错误消息

python - 从 BSE 网站提取数据

python - 查找子字符串在字符串中连续出现的次数最多

python - 在 python 中按日期范围过滤日志的最佳方法

python - Django JSON 字段。 'module' 对象没有属性 'JSONField'

python - 如何使用装饰器自动记录我的类属性

python - 在 Jinja 中根据 CSV 值创建列表