【发布时间】:2013-07-29 14:47:12
【问题描述】:
我正在尝试在我的 python 程序上设置 argparse,但它不起作用。 我试图处理的论点如下:
第一个参数为“--interactive”或整数,其中一个是必需的
“--xml”或“--html”或“--text”或“--console”中的任何一个。同样,它可以是其中任何一个,但第二个参数需要其中一个
最后对于第三个参数,'--verbose' 标志是可选的。
除了第一个参数的整数之外,所有这些参数都将变量更改为 True。
这是我手头的代码:
import argparse
parser = argparse.ArgumentParser(description='Python Historical Event Calculator.',
prog='tempus.py')
inputs = parser.add_mutually_exclusive_group(required=True)
exports = parser.add_mutually_exclusive_group(required=True)
inputs.add_argument('integer', metavar='I', type=float,
help='percentage to use')
inputs.add_argument('-i','--interactive', dest='bool_interactive',
action='store_true', help='enter interactive mode')
exports.add_argument('-x','--xml', dest='bool_xml', action='store_true',
help='export output as xml')
exports.add_argument('--html', dest='bool_html', action='store_true',
help='export output as html')
exports.add_argument('-t','--text', dest='bool_text', action='store_true',
help='export output as plaintext')
exports.add_argument('-c','--console', dest='bool_con', action='store_true',
help='export output to console')
parser.add_argument('-v','--verbose', dest='verbose', action='store_true',
help='enter verbose/debug mode', required=False)
args = parser.parse_args()
但我不知道我是否走在正确的轨道上,有人可以帮忙吗?这看起来是对的还是我做错了?
编辑
当我将任何标志传递给它时,我会得到这个回溯:
Traceback (most recent call last):
File "C:\Users\Callum\Dropbox\Tempus\Feature Tests\argparsetest.py", line 9, in <module>
help='percentage to use')
File "C:\Python32\lib\argparse.py", line 1305, in add_argument
return self._add_action(action)
File "C:\Python32\lib\argparse.py", line 1528, in _add_action
raise ValueError(msg)
ValueError: mutually exclusive arguments must be optional
【问题讨论】:
-
你为什么不简化和改变它,让你的
--xml、--html、--text、--console选项变成一个单独的标志,称为--output=x,其中x可以是xml、html、text或console,然后为其设置默认值?同样,--interactive可以是可选的,或者integer可以是可选的。否则,您将有更多的逻辑来确定什么优先于其他。 -
您有错误吗?如果是这样,请显示回溯。乍一看,即使您应该考虑 birryree 的论点,您的代码似乎也很实用。因此,如果您没有收到任何错误,您的帖子属于 -imho- 代码审查:codereview.stackexchange.com
-
@Birryree:我将如何将这些参数更改为该格式?
-
@DonQuestion:我已将回溯添加为编辑 :)