I often write commands that run on the command line in Python, but sometimes I want to write subcommands like git
.
For git
$ git commit -m "test"
This commit
is a subcommand.
Create this subcommand.
If you want to parse command arguments in Python, use the ** argparse ** module.
15.4. argparse — Command line options, arguments, subcommand parsers — http://docs.python.jp/2.7/library/argparse.html?highlight=argparse#argparse
Normally, you would import the ** ArgumentParser ** class from the argparse module. Then define the parser and add options.
Normal time :
normal.py
from argparse import argumentParser
parser = ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)
You need to nest parsers in order to create subcommands. ** You can set subcommands by installing another parser inside the parser. ** **
subcmd.py
>>> from argparse import ArgumentParser
>>>
>>> # create the top-level parser
>>> parser = ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', action='store_true', help='foo help')
>>> subparsers = parser.add_subparsers(help='sub-command help')
>>>
>>> # create the parser for the "a" command
>>> parser_a = subparsers.add_parser('a', help='a help')
>>> parser_a.add_argument('bar', type=int, help='bar help')
>>>
>>> # create the parser for the "b" command
>>> parser_b = subparsers.add_parser('b', help='b help')
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
>>>
>>> # parse some arg lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)
Create a wrapper for the subparser with the parser.add_subparsers
method and
subparsers = parser.add_subparsers(help='sub-command help')
Make a subparser from a wrapper.
parser_a = subparsers.add_parser('a', help='a help')
Give arguments to the subparser.
parser_a.add_argument('bar', type=int, help='bar help')
By the way, in the case of the above sample, the help message looks like this.
usage: PROG [-h] [--foo] {a,b} ...
positional arguments:
{a,b} sub-command help
a a help
b b help
optional arguments:
-h, --help show this help message and exit
--foo foo help
Now you can create subcommands.
Recommended Posts