argparse - 如何处理父解析器行为?
我有一个父解析器,它定义了一个通用标志 --global
,该标志在子解析器之间全局可用。
parent (defines --global)
/ \
child1 child2
--global --global
我正在通过 set_dfault。由于两个子解析器都继承 --global
我必须处理两个子解析器函数中的标志。我该如何改进这个?我可以在 parent
中定义一次 --global
的行为而不重复我吗?
parent = argparse.ArgumentParser(add_help=False)
parent.add_argument("--global", action="store_true")
def handle_child1(xargs):
if xargs.global:
print("handle global")
print("do stuff from child 1")
def handle_child2(yargs):
if yargs.global:
print("handle global")
print("do stuff from child 2")
subparser = parser.add_subparsers()
child1 = subparser.add_parser("c1", parents=[parent])
subparse_x.set_defaults(func=handle_child1)
child2 = subparser.add_parser("c2", parents=[parent])
subparse_y.set_defaults(func=handle_child2)
正如你所看到的,我必须在每个子解析器中处理全局。不知道。当然,我可以从每个子解析器调用一个函数 handle_global
来使这更好一些。但是,有没有一种解决方案可以让 parent
处理 global
呢?
I have a parent parser which defines a common flag --global
which is globally available across subparsers.
parent (defines --global)
/ \
child1 child2
--global --global
I am handling the flags of child1
and child2
via set_dfault. Since both subparsers inherit --global
I have to handle the flag in both subparser functions. How can I improve this? Can I define the behaviour of --global
in parent
once without repeating me?
parent = argparse.ArgumentParser(add_help=False)
parent.add_argument("--global", action="store_true")
def handle_child1(xargs):
if xargs.global:
print("handle global")
print("do stuff from child 1")
def handle_child2(yargs):
if yargs.global:
print("handle global")
print("do stuff from child 2")
subparser = parser.add_subparsers()
child1 = subparser.add_parser("c1", parents=[parent])
subparse_x.set_defaults(func=handle_child1)
child2 = subparser.add_parser("c2", parents=[parent])
subparse_y.set_defaults(func=handle_child2)
As you can see I have to handle global
in each subparser. Not idea. Of cause I could call a function handle_global
from each subparser to make this a bit better. However is there a solution that just lets parent
handle global
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解您正在尝试执行的操作,您可以在将参数发送到正确的子命令函数之前处理全局属性。
If I understand what you are attempting to do you can handle the global attribute prior to sending the arguments to the correct sub-command function.