小编Den*_*orn的帖子

如何在 python argparse 中使用子解析器定义全局选项?

我试图弄清楚如何使用 python arparse 库在子解析器场景中添加全局选项。

现在我的代码如下所示:

def parseArgs(self):
    parent_parser = argparse.ArgumentParser(add_help=False)
    parent_parser.add_argument('--debug', default=False, required=False,
        action='store_true', dest="debug", help='debug flag')

    main_parser = argparse.ArgumentParser()
    main_parser.add_argument('--debug', default=False, required=False,
        action='store_true', dest="debug", help='debug flag')

    service_subparsers = main_parser.add_subparsers(title="category",
        dest="category")
    agent_parser = service_subparsers.add_parser("agent",
        help="agent commands", parents=[parent_parser])
    return main_parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

这适用于命令行./test --help,并且该--debug选项被列为全局:

用法:测试 [-h] [--debug] {agent} ...

可选参数:
  -h, --help 显示此帮助消息并退出
  --debug 调试标志

类别:
  {代理人}
    代理 代理命令

但是,当我使用命令行触发代理子解析器时,./test agent --help该--debug选项现在不再列为全局选项,而是作为子解析器的选项。此外,它现在必须指定为./test agent --debug并且./test --debug agent不再有效:

用法:测试代理 [-h] [--debug]

可选参数:
  -h, …

python argparse

6
推荐指数
1
解决办法
3325
查看次数

标签 统计

argparse ×1

python ×1