Python argpase: Handling unknown amount of parameters/options/etc
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.Argumen开发者_如何学运维tParser(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).
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.
# -*- 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()
精彩评论