gpt4 book ai didi

Python optparse 不接受选项

转载 作者:太空宇宙 更新时间:2023-11-03 17:46:29 24 4
gpt4 key购买 nike

我编写了一个最多接受 4 个选项和 2 个参数的函数。选项包括 -1、-2、-3 和 -u。默认情况下,它们的值分别设置为 true、true、true 和 false,但启用任何选项都会导致该值翻转。问题是,即使我指定,比如说,

python comm.py -1 -2 -u test test2

并打印选项的值,它们仍然显示默认值。以下是我的代码的相关部分:

...
...
...
parser.add_option("-1", action="store_false", dest="xcol1", default=True, help="...")
parser.add_option("-2", action="store_false", dest="xcol2", default=True, help="...")
parser.add_option("-3", action="store_false", dest="dups", default=True, help="...")
parser.add_option("-u", action="store_true", dest="donotsort", default=False, help="...")

options, args = parser.parse_args(sys.argv[2:])

xcol1=options.xcol1
xcol2=options.xcol2
dups=options.dups
donotsort=options.donotsort


print "xcol1:"
print xcol1
print "xcol 2:"
print xcol2
print "dups:"
print dups
print "donotsort:"
print donotsort
print args
...
...
...

使用上述代码执行上述命令将输出:

正确

错误

正确

正确

测试,测试2

即默认值。它确实应该输出“False, False, True, True, ...),因为选项 1、2 和 u 已启用。我做错了什么?这与解析器有关吗,因为我不是100% 确定我正确使用了解析器。

此外,当我将选项列为 -12u 而不是 -1 -2 -u 时,它的行为有所不同 - bool 值不同

最佳答案

应该是

options, args = parser.parse_args()

同时添加:

print options

结果:

xcol1:
True
xcol 2:
True
dups:
True
donotsort:
False
['test', 'test2']
{'dups': True, 'donotsort': False, 'xcol2': True, 'xcol1': True}

说明:

sys.argv 是一个列表,类似于 [{myScript.py}, {args...}]。因此,sys.argv[2:] 会删除你的标志。

给定:

import sys
print sys.argv

结果:

>>> python showArgs.py -12u
>>> ['showArgs.py', '-12u']
<小时/>

此外,根据 the official docs , optparse 已弃用,取而代之的是 argparse .

关于Python optparse 不接受选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29724676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com