我有一个Python脚本,它运行两个接受相同选项( --config )的子命令。我想要创建一个第三个子命令,可以一起运行前两个子命令,顺序。
使用are解析,我为每个子命令创建了一个子解析器,并为第三个子解析器创建了一个子解析器,其父解析器是两个子命令。我只想澄清:
subcommand1 = subparsers.add_parser('subcommand1')
subcommand1.add_argument('--config', help="The config")
subcommand2 = subparsers.add_parser('subcommand2')
subcommand2.add_argument('--config', help="The config")
wrappercommand = subparsers.add_parser('wrappercommand',
parents=[subcommand1, subcommand2],
conflict_handler='resolve')当我运行包装命令或subcommand2时,一切都能正常工作。但是,subcommand1中断了,并将其作为输出:
$ run_command.py subcommand1 --config path_to_config.ini
usage: run_command.py subcommand1 config
optional arguments:
help show this help message and exit
config The config看起来arg解析将关键字arg(“-config”)转换为位置关键字arg ("config")。这是否是由are解析解决冲突选项时的预期行为?
发布于 2014-09-13 07:48:18
我认为你是在把这个冲突处理者推进到非故意和未经测试的领域。通常,parents是不被使用的独立解析器。它们只是Actions的一个来源。与-h有关的冲突由add_help=False处理。
作为背景:使用默认的conflict_handler (错误),您将在创建wrappercommand子解析器时获得错误消息:
argparse.ArgumentError: argument -h/--help: conflicting option string(s): -h, --help添加了一些add_help=False之后,您仍然可以得到:
argparse.ArgumentError: argument --config: conflicting option string(s): --configresolve冲突处理程序将错误消息替换为某种“解决方案”。下面的脚本演示了正在发生的事情。
resolve处理程序删除subcommand1操作的option_strings,同时保留操作。实际上,这两者都变成了位置。而且,由于help有nargs=0,所以它总是运行。因此,帮助显示。
_handle_conflict_resolve的目的是删除第一个参数的证据,因此可以添加新的参数。当冲突是由两个具有相同选项字符串的add_argument命令产生时,这很好。但在这里,这种冲突是由来自父母的“抄袭”行为造成的。但是父操作是通过引用复制的,因此“子”中的更改最终会影响“父”。
一些可能的解决办法:
wrappercommand。这个parents机制只是将父母的参数添加到孩子身上。它不会按顺序“运行”父母。_handle_conflict_...函数以正确解决冲突。parents处理程序而使用resolve。我在这个示例http://bugs.python.org/issue22401中提交了一个bug报告:
parent1 = argparse.ArgumentParser(add_help=False)
parent1.add_argument('--config')
parent2 = argparse.ArgumentParser(add_help=False)
parent2.add_argument('--config')
parser = argparse.ArgumentParser(parents=[parent1,parent2],
conflict_handler='resolve')
def foo(parser):
print [(id(a), a.dest, a.option_strings) for a in parser._actions]
foo(parent1)
foo(parent2)
foo(parser)它产生:
[(3077384012L, 'config', [])]
[(3076863628L, 'config', ['--config'])]
[(3076864428L, 'help', ['-h', '--help']), (3076863628L, 'config', ['--config'])]注意,缺少的option_strings用于parent1,与其他2. parent1匹配的id不能再次用作父级或解析器。
argparse - Combining parent parser, subparsers and default values是另一种情况,通过引用复制父级操作会造成复杂性(更改默认值)。
https://stackoverflow.com/questions/25818651
复制相似问题