Describes how to use argparse to parse subcommands in Python 3. However, I'm not familiar with Python, so there may be a better way. I want to use only the standard library, but argparse is too sophisticated to use ...
git add
or git commit
like the git
commandgit help
The points are as follows.
parser
withparser.add_subparsers ()
parser_〇〇.set_defaults (handler = function name)
to transfer the processing for each subcommand to the handler function.git.py
#!/usr/bin/env python
# coding: utf-8
import argparse
#Callback function that describes the actual processing of the subcommand
def command_add(args):
print(args)
def command_commit(args):
print(args)
def command_help(args):
print(parser.parse_args([args.command, '--help']))
#Create command line parser
parser = argparse.ArgumentParser(description='Fake git command')
subparsers = parser.add_subparsers()
#Create parser for add command
parser_add = subparsers.add_parser('add', help='see `add -h`')
parser_add.add_argument('-A', '--all', action='store_true', help='all files')
parser_add.set_defaults(handler=command_add)
#Create parser for commit command
parser_commit = subparsers.add_parser('commit', help='see `commit -h`')
parser_commit.add_argument('-m', metavar='msg', help='commit message')
parser_commit.set_defaults(handler=command_commit)
#Create parser for help command
parser_help = subparsers.add_parser('help', help='see `help -h`')
parser_help.add_argument('command', help='command name which help is shown')
parser_help.set_defaults(handler=command_help)
#Parse command line arguments and execute the corresponding handler function
args = parser.parse_args()
if hasattr(args, 'handler'):
args.handler(args)
else:
#Get help for unknown subcommands
parser.print_help()
If you do not specify a subcommand, the top-level help message is displayed.
$ python git.py
usage: git.py [-h] {commit,add,help} ...
Fake git command
positional arguments:
{commit,add,help}
commit see `commit -h`
add see `add -h`
help see `help -h`
optional arguments:
-h, --help show this help message and exit
If you add the -h
option to a subcommand, a subcommand level help message is displayed. This is because argparse does a good job.
$ python git.py commit -h
usage: git.py commit [-h] [-m msg]
optional arguments:
-h, --help show this help message and exit
-m msg commit message
The same is true when using the help
subcommand. This is because I implemented it myself.
$ python git.py help commit
usage: git.py commit [-h] [-m msg]
optional arguments:
-h, --help show this help message and exit
-m msg commit message
Finally, the ʻaddand
commit` subcommands also work as expected.
$ python git.py add
Namespace(all=False, handler=<function command_add at 0x102973c80>)
$ python git.py commit -m "message"
Namespace(handler=<function command_commit at 0x10510e7b8>, m='message')
Recommended Posts