Specify a subcommand as a command line argument in Python

Introduction

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.

Implementation

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

Specify a subcommand as a command line argument in Python
How to get a string from a command line argument in python
Command line argument processing (Python docopt)
Decompose command arguments in one line in Python
A note I looked up to make a command line tool in Python
Template for creating command line applications in Python
How to receive command line arguments in Python
Make a rock-paper-scissors game in one line (python)
Build a command line app in Python to understand setup.py, argparse, GitHub Actions
How to manage arguments when implementing a Python script as a command line tool
[LINE Messaging API] Create a rich menu in Python
How to execute a command using subprocess in Python
I implemented a Vim-like replacement command in Slackbot #Python
Create a function in Python
Create a dictionary in Python
Fizzbuzz in Python (in one line)
Execute external command in python
Try LINE Notify in Python
Make a bookmarklet in Python
External command execution in Python
Draw a heart in Python
Displaying DICOM images in rudimentary Python as a medical professional
Allow brew install of command line tools made in Python
A story about how to specify a relative path in python.
Grayscale image is displayed as a color image in OpenCV / Python
How to specify command line arguments when debugging in PyCharm
[python] Manage functions in a dictionary (command table, function table, function pointer)
Maybe in a python (original title: Maybe in Python)
Use pymol as a python library
[python] Callback function (pass function as argument)
[python] Manage functions in a list
Function argument type definition in python
[Python] Create a program to delete line breaks in the clipboard + Register as a shortcut with windows
python Note: Determine if command line arguments are in the list
Use fabric as is in python (fabric3)
Create a DI Container in Python
Run shell command / python in R
Format when passing a long string as an argument of python
Draw a scatterplot matrix in python
ABC166 in Python A ~ C problem
Write A * (A-star) algorithm in Python
Read the standard output of a subprocess line by line in Python
In the python command python points to python3.8
Create a binary file in Python
Investigating what could be used as a Markdown parser in Python
Use blender as a python module
Solve ABC036 A ~ C in Python
Write a pie chart in Python
Write a vim plugin in Python
Write a depth-first search in Python
Implementing a simple algorithm in Python 2
Create a Kubernetes Operator in Python
Solve ABC037 A ~ C in Python
Launch a Python script as a service
Run a simple algorithm in Python
Draw a CNN diagram in Python
Create a random string in Python
Get the formula in an excel file as a string in Python
I tried Line notification in Python
[Introduction] Insert line breaks in Python 3
Implemented in 1 minute! LINE Notify in Python