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)。
1 个回答
3
这个问题的简单答案是使用 argparse.ArgumentParser.parse_known_args 这个方法。这个方法会解析你脚本中已经知道的参数,而忽略其他的参数。
下面是我根据你提供的代码写的一些内容。
# -*- coding: utf-8 -*-
import argparse
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='command', help='commands')
vcs = subparsers.add_parser('vcs', help='control the vcs')
vcs_main = vcs.add_subparsers(dest='vcs_command', help='vcs commands')
vcs_commit = vcs_main.add_parser('commit',
help="Commit changes into a new revision")
vcs_checkout = vcs_main.add_parser('checkout',
help="Create a new checkout of an "
"existing branch")
args, other_args = parser.parse_known_args()
if args.command == 'vcs':
if args.vcs_command == 'commit':
print("call the wrapped command here...")
print(" bzr commit %s" % ' '.join(other_args))
elif args.vcs_command == 'checkout':
print("call the wrapped command here...")
print(" bzr checkout %s" % ' '.join(other_args))
return 0
if __name__ == '__main__':
main()