对 argparse 使用一个标志参数或两个位置参数 [英] Use either one flag argument or two positional arguments with argparse

查看:26
本文介绍了对 argparse 使用一个标志参数或两个位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在一项任务上,如果启用标志,则需要 2 个位置参数或 1 个(文件):

i'm stuck on a task, which require either 2 positional args or 1 (a file) if flag enabled:

parser.add_argument('pos_arg1', help='desc')
parser.add_argument('pos_arg2', help='desc')
parser.add_argument('--add_arg1', help='desc', type=argparse.FileType('r'), nargs='?')

因此将脚本与 script.py arg1 arg2script.py --add_arg1 file 一起使用都是有效的.我该怎么做?

so using the script with either script.py arg1 arg2 or script.py --add_arg1 file are both valid. How would I do this?

推荐答案

如果你定义:

In [422]: parser=argparse.ArgumentParser()    
In [423]: g=parser.add_mutually_exclusive_group()
In [424]: g.add_argument('--foo')
In [426]: g.add_argument('bar',nargs='*',default='test')

In [427]: parser.print_help()
usage: ipython2.7 [-h] [--foo FOO | bar [bar ...]]

positional arguments:
  bar

optional arguments:
  -h, --help  show this help message and exit
  --foo FOO

In [429]: parser.parse_args([])
Out[429]: Namespace(bar='test', foo=None)

In [430]: parser.parse_args(['one','two'])
Out[430]: Namespace(bar=['one', 'two'], foo=None)

In [431]: parser.parse_args(['--foo','two'])
Out[431]: Namespace(bar='test', foo='two')

通过它,您可以指定两个(实际上是任意数量)未标记的值,或一个用 --foo 标记的值.如果我两者都尝试,它会反对.我可以将组标记为 required.

With this you can specify two (really any number) of unlabeled values, or one value flagged with --foo. It will object if I try both. I could have marked the group as required.

一些注意事项:

--foo 标记为 nargs='?' 相对没有意义,除非我同时指定 defaultconst.

Marking --foo as nargs='?' is relatively meaningless unless I specify both a default and const.

我只能在独占组中指定一个位置,并且该参数必须有'?'或*"和默认".换句话说,它必须是真正可选的.

I can only specify one one positional in the exclusive group, and that argument has to have '?' or '*', and a 'default'. In other words, it has to genuinely optional.

如果没有mutual_exclusive_group,我可以创建两个位置?,但我不能说零或两个参数".

Without the mutually_exclusive_group I could make both positionals ?, but I can't say 'zero or two arguments'.

这篇关于对 argparse 使用一个标志参数或两个位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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