Implement subcommands with Python's argparse

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 ...

Thing you want to do

Sample code

The points are as follows.

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()

Execution example

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 ʻaddandcommit` 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')

Reference information

Recommended Posts

Implement subcommands with Python's argparse
Easily implement subcommands with python click
Implement FReLU with tf.keras
Implement PyTorch + GPU with Docker
[QtDesigner] Implement WebView with PyQt5
Implement blockchain with about 60 lines
Feel free to implement Python's asynchronous http client with Trio + httpx
Debug email sending with Python's smtpd.DebuggingServer
(Note) Be careful with python argparse
Sort names with Python's random module
Implement Keras LSTM feedforward with numpy
Manage filters with Python's -m option # 2
Try mining Bitcoin with Python's hashlib
Be careful with Python's append method
Try using Python's networkx with AtCoder
Website scraping with Python's Beautiful Soup
Implement "Data Visualization Design # 2" with matplotlib