带有 nargs 行为的 Python argparse 不正确 [英] Python argparse with nargs behaviour incorrect

查看:21
本文介绍了带有 nargs 行为的 Python argparse 不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 argparse 样本说 sample.py

Here is my argparse sample say sample.py

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-p", nargs="+", help="Stuff")
args = parser.parse_args()
print args

Python - 2.7.3

Python - 2.7.3

我希望用户在 -p 选项后提供一个由空格分隔的参数列表.例如,如果您运行

I expect that the user supplies a list of arguments separated by spaces after the -p option. For example, if you run

$ sample.py -p x y 
Namespace(p=['x', 'y'])

但我的问题是当你运行时

But my problem is that when you run

$ sample.py -p x -p y
Namespace(p=['y'])

既不在这里也不在那里.我想要以下之一

Which is neither here nor there. I would like one of the following

  • 向用户抛出一个异常,要求他不要使用 -p 两次,而是将它们作为一个参数提供
  • 假设它是相同的选项并生成一个 ['x','y'] 列表.

我可以看到 python 2.7 没有做这两个,这让我很困惑.我可以让 python 执行上面记录的两种行为之一吗?

I can see that python 2.7 is doing neither of them which confuses me. Can I get python to do one of the two behaviours documented above?

推荐答案

注意:python 3.8 添加了一个 action="extend",它将创建所需的 ['x','y'] 列表

Note: python 3.8 adds an action="extend" which will create the desired list of ['x','y']

要生成 ['x','y'] 的列表,请使用 action='append'.其实它给了

To produce a list of ['x','y'] use action='append'. Actually it gives

Namespace(p=[['x'], ['y']])

对于每个-p,它给出一个列表['x'],由nargs='+' 指示,但是append 表示将该值添加到命名空间已有的值中.默认操作只是设置值,例如NS['p']=['x'].我建议查看文档中的 action 段落.

For each -p it gives a list ['x'] as dictated by nargs='+', but append means, add that value to what the Namespace already has. The default action just sets the value, e.g. NS['p']=['x']. I'd suggest reviewing the action paragraph in the docs.

optionals 允许重复使用设计.它启用诸如 appendcount 之类的操作.通常用户不希望重复使用它们,或者对最后一个值感到满意.positionals(没有-flag)不能重复(除非nargs允许).

optionals allow repeated use by design. It enables actions like append and count. Usually users don't expect to use them repeatedly, or are happy with the last value. positionals (without the -flag) cannot be repeated (except as allowed by nargs).

如何添加可选或一次性参数? 有一些关于如何创建无重复"论点的建议.一种是创建自定义action 类.

How to add optional or once arguments? has some suggestions on how to create a 'no repeats' argument. One is to create a custom action class.

这篇关于带有 nargs 行为的 Python argparse 不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆