当我运行./foo.py -h时,其中foo.py是以下代码,它会因错误而崩溃
ValueError:要解压缩的值太多
这是代码。
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description='Find matrices.')
parser.add_argument('integers', metavar=('n','h'), type=int, nargs=2, help='Dimensions of the matrix')
(n,h)= parser.parse_args().integers
我的代码中是否有错误?
完全追溯(Python 2.7.3):
Traceback (most recent call last):
File "argp.py", line 15, in <module>
(n,h)= parser.parse_args().integers
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 1720, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "/usr/lib/python2.7/argparse.py", line 1926, in _parse_known_args
start_index = consume_optional(start_index)
File "/usr/lib/python2.7/argparse.py", line 1866, in consume_optional
take_action(action, args, option_string)
File "/usr/lib/python2.7/argparse.py", line 1794, 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 2313, in print_help
self._print_message(self.format_help(), file)
File "/usr/lib/python2.7/argparse.py", line 2280, in format_help
formatter.add_arguments(action_group._group_actions)
File "/usr/lib/python2.7/argparse.py", line 273, in add_arguments
self.add_argument(action)
File "/usr/lib/python2.7/argparse.py", line 258, in add_argument
invocations = [get_invocation(action)]
File "/usr/lib/python2.7/argparse.py", line 534, in _format_action_invocation
metavar, = self._metavar_formatter(action, action.dest)(1)
ValueError: too many values to unpack
答案 0 :(得分:8)
这是argparse
中的一个错误,其中nargs
,元组metavar
和位置参数不混合。 integers
是位置参数,而不是可选的--integers
开关。
要么使它成为可选参数:
parser.add_argument('--integers', metavar=('n','h'), type=int, nargs=2, help='Dimensions of the matrix')
或使用两个位置参数:
parser.add_argument('n', type=int, help='Dimensions of the matrix')
parser.add_argument('h', type=int, help='Dimensions of the matrix')
代替。
请参阅Python bug跟踪器中的issue 14074以获取针对该错误的建议修复。