3

在我的脚本中,我尝试包装集市可执行文件。当我阅读某些适用于 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)。

4

1 回答 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()
于 2011-09-09T17:40:03.280 回答