我试图在我的python程序上设置argparse,但它不工作。是 我试图过程的参数如下:在Python 3.2上设置argparse
是“--interactive”,或者是对第一个参数整数,这些需要一个
中的任何一个是“--xml” OR '--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 2012-02-23 21:45:52
你有错误吗?如果是这样,请显示回溯。乍一看,如果你应该考虑birryree的论点,你的代码甚至看起来很有用。所以,如果你没有得到任何错误,你的帖子属于-imho-代码审查:http://codereview.stackexchange。com/ – 2012-02-23 21:49:15
@Birryree:我会如何改变这些格式的参数? – 2012-02-23 21:51:43