在使用-h时,python argparse崩溃了

 啊哈哈 发布于 2023-02-09 11:28

当我运行./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 
    (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

Martijn Piet.. 9

这是一个错误,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错误跟踪器中的问题14074以获取针对该错误的建议修复.

1 个回答
  • 这是一个错误,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错误跟踪器中的问题14074以获取针对该错误的建议修复.

    2023-02-09 11:29 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有