【发布时间】:2020-09-26 18:06:09
【问题描述】:
我有一组解析器和子解析器来构建生产或开发系统。
如果用户选择生产,他可以添加选项,一切都很好。
如果他了解开发,他可以输入架构,然后输入构建选项。
这是它变得粘稠的地方。
我希望他能够选择构建选项 'comms' 'server' 或 'all',但如果他选择服务器,他有更多选择。
我的实现如下。我尝试了解析器和子解析器的组合 (看来参数只能添加到解析器,不能添加子解析器,对吗?)
它分崩离析有两个原因:
1)我只能选择arch或build,我需要同时选择
2)如果我选择构建它总是要求我选择“服务器”,即使我选择其他两个之一。
所以我想要这样的东西 ./buildServer.py 开发架构 -arm build -comms 要么 ./buildServer.py Dev arch -arm build -server -tcp
我将不胜感激并能获得帮助/指导 - TIA
代码:
def 验证():
main_parser = argparse.ArgumentParser()
main_subparsers = main_parser.add_subparsers(title="main", dest="main_command")
# parser production choices
prod_parser = main_subparsers.add_parser("prod", help="Prod")
prod_parser.add_argument("-c", "--change", action='store_true', dest="change_sig", default=False, help="Change signature information (default = %(default)s)")
prod_parser.add_argument("-sd", "--sign-deb", action='store_true', dest="sign_deb", default=False, help="Add signature to the .deb file (default = %(default)s)")
prod_parser.add_argument ("-i", "--install", action='store_true', dest="build_deb" , default=False, help="Build .deb file from existing structure (default = %(default)s)")
# parser for development
dev_parser = main_subparsers.add_parser("Dev", help="Dev")
dev_subparser = dev_parser.add_subparsers(title="devsubparser")
# optional development architecture choices
action_arch_parser = dev_subparser.add_parser("arch", help="architecture")
dev_arch_group = action_arch_parser.add_mutually_exclusive_group()
dev_arch_group.add_argument("-x86", action='store_const', dest="architecture", const='x', default='x',help="Build dev code on X86")
dev_arch_group.add_argument("-arm", action='store_const', dest="architecture", const='a', help="Build dev code on arm")
# development build choices - 2 arguments (coms / all) and a third (server) that has its own options.
dev_build_parser = dev_subparser.add_parser("build", help="build")
dev_build_parser.add_argument("-comms", action='store_true', help="Build comms program")
dev_build_parser.add_argument("-all", action='store_true', help="Build all programs")
server_parser = dev_build_parser.add_subparsers(title="server", help="server subparser")
server_parser_p = server_parser.add_parser("server", help="server parser")
server_parser_p.add_argument("-tcp", help="tcp option")
server_parser_p.add_argument("-fips", help="fips option")
server_parser_p.add_argument("-sim", help="sim option")
args = main_parser.parse_args()
【问题讨论】:
标签: python argparse optional-arguments subparsers