在解析器/子解析器的开头使用argparse.REMAINDER [英] Using argparse.REMAINDER at beginning of parser / sub parser
问题描述
我想实现一个允许我将unittest作为子命令之一运行的arg解析器,将参数盲目传递给unittest.main().例如,
I want to implement an arg parser that allows me to run unittests as one of the sub commands, blindly passing the arguments on to unittest.main(). e.g.,
$ foo.py unittest [args to pass to unittest.main()]
以及其他子命令:
$ foo.py foo ...
$ foo.py bar ...
以argparse的示例为例,该方法有效:
Following argparse's example, this works:
#!/usr/bin/python
import argparse
p = argparse.ArgumentParser(prog='PROG')
p.add_argument('-v', '--verbose', action='store_true')
sub = p.add_subparsers(dest='cmd')
foo = sub.add_parser('foo')
bar = sub.add_parser('bar')
unittest = sub.add_parser('unittest')
unittest.add_argument('command') # Need to add this to make it work.
unittest.add_argument('args', nargs=argparse.REMAINDER)
print(p.parse_args('unittest command -blah blah'.split()))
输出:
Namespace(args=['-blah', 'blah'], cmd='unittest', command='command', verbose=False)
但这不是.似乎首先需要一个正常"参数:
But this doesn't. It seems to require a "normal" argument first:
#!/usr/bin/python
import argparse
p = argparse.ArgumentParser(prog='PROG')
p.add_argument('-v', '--verbose', action='store_true')
sub = p.add_subparsers(dest='cmd')
foo = sub.add_parser('foo')
bar = sub.add_parser('bar')
unittest = sub.add_parser('unittest')
unittest.add_argument('args', nargs=argparse.REMAINDER)
print(p.parse_args('unittest -blah blah'.split()))
输出:
$ /tmp/foo.py
usage: PROG [-h] [-v] {foo,bar,unittest} ...
PROG: error: unrecognized arguments: -blah
我可以做print(p.parse_args('unittest -- -f -g'.split()))
,但是要求--
失败会破坏argparse.REMAINDER的目的.
I can do print(p.parse_args('unittest -- -f -g'.split()))
, but requiring --
kind of defeats the purpose of argparse.REMAINDER.
有没有办法让argparse
做我想做的事情?还是我只需要手工分析这种情况?
Is there a way to get argparse
to do what I want? Or do I just need to hand parse this case?
Python 2.7.5
Python 2.7.5
推荐答案
类似于 http:中讨论的相同问题://bugs.python.org/issue17050 ,argparse.REMAINDER doesn't work as first argument
我4年前的推论仍然成立-在REMAINDER
有机会采取行动之前,-blah
被归类为可选标志. '-'是较早解析的,但在某种意义上...
只是对'*'的概括.而不是一个广泛使用的.对于'subparsers'操作而言,它具有一个nargs='+...'
值(argparse.PARSER
)-就像REMAINDER,不同之处在于它至少需要一个字符串'cmd'.
My deduction from 4 years ago still holds - the -blah
is being classed as an optional's flag even before REMAINDER
has a chance to act. '--' is parsed earlier, but ...
is, in a sense just a generalization of '*'. And not a widely used one. For what it's worth the 'subparsers' Action has a nargs='+...'
value (argparse.PARSER
) - it's like REMAINDER except it requires at least one string, the 'cmd'.
尚未执行 http://bugs.python.org/issue9334 中的可能修复程序在.因此,您要么需要自己处理'-blah',要么使用'-'. parse_known_args
也可能适用于您的情况.
The possible fix in http://bugs.python.org/issue9334 has not been acted on. So you either need to handle the '-blah' by itself, or use '--'. parse_known_args
might also work in your case.
这篇关于在解析器/子解析器的开头使用argparse.REMAINDER的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!