Python argpase:处理未知数量的参数/选项/等
在我的脚本中,我尝试包装 bazaar 可执行文件。当我读到 bzr 的某些选项时,我的脚本会对此做出反应。无论如何,所有参数都会传递给 bzr 可执行文件。当然我不想指定 bzr 可以在里面处理的所有参数 我的剧本。
那么,有没有办法用 argpase 处理未知数量的参数呢?
我的代码目前如下所示:
parser = argparse.ArgumentParser(help='vcs')
subparsers = parser.add_subparsers(help='commands')
vcs = subparsers.add_parser('vcs', help='control the vcs',
epilog='all other arguments are directly passed to bzr')
vcs_main = vcs.add_subparsers(help='vcs commands')
vcs_commit = vcs_main.add_parser('commit', help="""Commit changes into a
new revision""")
vcs_commit.add_argument('bzr_cmd', action='store', nargs='+',
help='arugments meant for bzr')
vcs_checkout = vcs_main.add_parser('checkout',
help="""Create a new checkout of an existing branch""")
nargs 选项当然允许我想要的参数。但不是另一个未知的可选参数(如 --fixes 或 --unchanged)。
in my script I try to wrap the bazaar executable. When I read certain options meant for bzr my script will react on that. In any case all arguments are then given to the bzr executable. Of course I don't want to specify all arguments that bzr can handle inside
my script.
So, is there a way to handle an unknown amount of arguments with argpase?
My code currently looks like this:
parser = argparse.ArgumentParser(help='vcs')
subparsers = parser.add_subparsers(help='commands')
vcs = subparsers.add_parser('vcs', help='control the vcs',
epilog='all other arguments are directly passed to bzr')
vcs_main = vcs.add_subparsers(help='vcs commands')
vcs_commit = vcs_main.add_parser('commit', help="""Commit changes into a
new revision""")
vcs_commit.add_argument('bzr_cmd', action='store', nargs='+',
help='arugments meant for bzr')
vcs_checkout = vcs_main.add_parser('checkout',
help="""Create a new checkout of an existing branch""")
The nargs option allows as many arguments as I want of course. But not another unknown optional argument (like --fixes or --unchanged).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题的简单答案是使用 argparse.ArgumentParser.parse_known_args< /a> 方法。这将解析您的包装脚本已知的参数并忽略其他参数。
这是我根据您提供的代码输入的内容。
The simple answer to this question is the usage of the argparse.ArgumentParser.parse_known_args method. This will parse the arguments that your wrapping script knowns about and ignore the others.
Here is something I typed up based on the code that you supplied.