Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python argparse crashes when using -h

When I run ./foo.py -h where foo.py is the following code it crashes with the error

ValueError: too many values to unpack

Here is the code.

#!/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

Is there a bug in my code?

Full traceback (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
like image 725
marshall Avatar asked Dec 19 '13 11:12

marshall


1 Answers

This is a bug in argparse where nargs, a tuple metavar and positional arguments do not mix. integers is a positional argument, not an optional --integers switch.

Either make it an optional argument:

parser.add_argument('--integers', metavar=('n','h'), type=int, nargs=2, help='Dimensions of the matrix')

or use two positional arguments:

parser.add_argument('n', type=int, help='Dimensions of the matrix')
parser.add_argument('h', type=int, help='Dimensions of the matrix')

instead.

See issue 14074 in the Python bug tracker for proposed fix for the bug.

like image 108
Martijn Pieters Avatar answered Nov 10 '22 11:11

Martijn Pieters