与所有开关一起编程,运行良好,但argparse' - help'抛出了很多错误

时间:2015-01-30 15:25:59

标签: python debugging argparse

我在Python中使用argparse来处理程序中的参数。例如,如下所示,如果我使用参数'-p',则执行特定模块。现在,所有论点和程序运行良好。但是当我尝试为我的程序获取' - help'时,它会崩溃(图像)。

以下是与argparse相关的代码:

parser = argparse.ArgumentParser(description="something1.")
parser.add_argument('-x', '--xoo', help='something2', action='store_true')
parser.add_argument('-a', '--al', help='something3', action='store_true')
parser.add_argument('-c', '--conv', help='something4', type=float)
parser.add_argument('-p', '--pay', help='something5', type=float)
args = parser.parse_args()

关于如何纠正此错误的任何想法??

$ ./xoom.py -h
Traceback (most recent call last):
  File "./xoom.py", line 46, in <module>
    args = parser.parse_args()
  File "/usr/lib/python2.7/argparse.py", line 1688, in parse_args
    args, argv = self.parse_known_args(args, namespace)
  File "/usr/lib/python2.7/argparse.py", line 1723, in parse_known_args
    namespace, args = self._parse_known_args(args, namespace)
  File "/usr/lib/python2.7/argparse.py", line 1929, in _parse_known_args
    start_index = consume_optional(start_index)
  File "/usr/lib/python2.7/argparse.py", line 1869, in consume_optional
    take_action(action, args, option_string)
  File "/usr/lib/python2.7/argparse.py", line 1797, in take_action
    action(self, namespace, argument_values, option_string)
  File "/usr/lib/python2.7/argparse.py", line 994, in __call__
    parser.print_help()
  File "/usr/lib/python2.7/argparse.py", line 2319, in print_help
    self._print_message(self.format_help(), file)
  File "/usr/lib/python2.7/argparse.py", line 2293, in format_help
    return formatter.format_help()
  File "/usr/lib/python2.7/argparse.py", line 279, in format_help
    help = self._root_section.format_help()
  File "/usr/lib/python2.7/argparse.py", line 209, in format_help
    func(*args)
  File "/usr/lib/python2.7/argparse.py", line 209, in format_help
    func(*args)
  File "/usr/lib/python2.7/argparse.py", line 515, in _format_action
    help_text = self._expand_help(action)
  File "/usr/lib/python2.7/argparse.py", line 601, in _expand_help
    return self._get_help_string(action) % params
TypeError: float argument required, not dict

1 个答案:

答案 0 :(得分:8)

问题是您的something4和/或something5中有%字符。

删除它们,看看是否仍然出现错误。

如果您确实需要这些帮助文本中的%字符,请尝试使用%%替换它们 - 即连续使用2%的字符。

更新:这是一个最小的例子,它说明了你收到错误的原因:

import argparse

parser = argparse.ArgumentParser(description="something1.")
parser.add_argument('-c', '--conv', help='somet%fhing4', type=float)
args = parser.parse_args()

使用--help运行以生成错误消息。请注意帮助字符串中的%字符。