关于python:如何使用argparse解析带有前导减号(负数)的位置参数 您所在的位置:网站首页 python的减号 关于python:如何使用argparse解析带有前导减号(负数)的位置参数

关于python:如何使用argparse解析带有前导减号(负数)的位置参数

2024-04-09 22:09| 来源: 网络整理| 查看: 265

我想解析一个包含以逗号分隔的整数列表的必需的位置参数。 如果第一个整数包含一个前导减号(' - '),argparse会抱怨:

1234567891011121314151617import argparse parser = argparse.ArgumentParser() parser.add_argument('positional') parser.add_argument('-t', '--test', action='store_true') opts = parser.parse_args() print opts $ python example.py --test 1,2,3,4 Namespace(positional='1,2,3,4', test=True) $ python example.py --test -1,2,3,4 usage: example.py [-h] [-t] positional example.py: error: too few arguments $ python example.py --test"-1,2,3,4" usage: example.py [-h] [-t] positional example.py: error: too few arguments

我见过人们建议使用除-之外的其他字符作为标志字符,但我宁愿不这样做。 是否有另一种方法来配置argparse以允许--test和-1,2,3,4作为有效参数?

相关讨论 万一有人需要这个,如果--test接受了参数,你可以这样做:python example.py --test=-1,2,3,4

您需要在命令行参数中插入--:

12$ python example.py --test -- -1,2,3,4 Namespace(positional='-1,2,3,4', test=True)

双击阻止argparse寻找更多可选开关; 这是命令行工具正好处理这个用例的事实标准方法。

相关讨论 啊,我不知道必须使用双破折号的标准(仍然是各种各样的* nix新手,仍在学习...)感谢您的信息! 这只是给了我error: unrecognized arguments: --(在Python 2.7.3下的argparse) @panzi:Python 2.7.5下没有这样的问题。

从文档:

The parse_args() method attempts to give errors whenever the user has clearly made a mistake, but some situations are inherently ambiguous. For example, the command-line argument -1 could either be an attempt to specify an option or an attempt to provide a positional argument. The parse_args() method is cautious here: positional arguments may only begin with - if they look like negative numbers and there are no options in the parser that look like negative numbers:

由于-1,2,3,4看起来不像负数,因此必须像大多数* nix系统中的--一样"逃避"它。

另一种解决方案是使用nargs作为位置,并将数字作为空格分隔传递:

1234567#test.py import argparse parser = argparse.ArgumentParser() parser.add_argument('positional', nargs='*') #'+' for one or more numbers print parser.parse_args()

输出:

12$ python test.py -1 2 3 -4 5 6 Namespace(positional=['-1', '2', '3', '-4', '5', '6'])

获得所需内容的第三种方法是使用parse_known_args而不是parse_args。 您不会将位置参数添加到解析器并手动解析它:

12345678import argparse parser = argparse.ArgumentParser() parser.add_argument('--test', action='store_true') parsed, args = parser.parse_known_args() print parsed print args

结果:

123$ python test.py  --test -1,2,3,4                                             Namespace(test=True) ['-1,2,3,4']

这样做的缺点是帮助文本信息量较少。

相关讨论 我看到了文档,但想知道是否有任何改变标准行为的技巧。 在这一点上,我认为最好需要四个单独的位置参数或使用空格分隔符而不是使用--转义机制。 谢谢您的帮助。 @Inactivist我用第三种方法更新了我的答案,以允许-1,2,3,4样式位置。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有