让 argparse 收集但不响应标志 [英] Have argparse collect, but not respond to, flags
问题描述
我有一个脚本,它接受一些参数,使用其中一些参数来选择要运行的脚本,并将其余参数传递给该脚本.所以它看起来像这样:
I have a script which takes in some arguments, uses some of those argument to choose a script to run, and passes the rest of the arguments to that script. So it looks something like this:
parser = ArgumentParser()
parser.add_argument('script', choices['a', 'b'])
parser.add_argument('rest_args', nargs='*')
args = parser.parse_args()
if args.script == 'a':
subprocess.call('python a.py %s' % ' '.join(args.rest_args))
else:
subprocess.call('python b.py %s' % ' '.join(args.rest_args))
这很好用,除非我想传入以 -
开头的参数.例如,如果我调用 python my_script.py a --foo
,我会得到一个错误 unrecognized arguments
,当我真的想让它运行 python a.py --foo
(即只需将 --foo
传递给子进程).
This works fine, unless I want to pass in arguments that start with -
. For example, if I called python my_script.py a --foo
, I'd get an error unrecognized arguments
, when really I want to just have it run python a.py --foo
(i.e. just pass the --foo
along to the subprocess).
有没有办法用 argparse
解决这个问题?
Is there a way to get around this with argparse
?
推荐答案
也许您正在寻找 parse_known_args.它将解析它识别的所有选项,并返回 unknown
中所有无法识别的参数:
Perhaps you are looking for parse_known_args. It will parse all the options it recognizes, and returns all the unrecognized arguments in unknown
:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('script', choices=['a', 'b'])
args, unknown = parser.parse_known_args(['a', '--foo'])
print(args)
# Namespace(script='a')
print(unknown)
# ['--foo']
这篇关于让 argparse 收集但不响应标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!