Skip to content

Instantly share code, notes, and snippets.

@timhughes
Last active March 29, 2020 16:37
Show Gist options
  • Save timhughes/4c267fa6bc51d4c2f7db667a007a2fe4 to your computer and use it in GitHub Desktop.
Save timhughes/4c267fa6bc51d4c2f7db667a007a2fe4 to your computer and use it in GitHub Desktop.
Different methods of creating subcommands with argparse
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 Tim Hughes <[email protected]>
#
# Distributed under terms of the MIT license.
"""
"""
import sys
import argparse
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def server(args):
try:
logger.info(f"Running server {args}")
pass
except KeyboardInterrupt:
logger.info("Exiting on KeyboardInterrupt")
except Exception as exc:
logger.info(f"Exiting on unknown error {exc}")
def initdb(args):
logger.info(f"Initializing database")
pass
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
parser_server = subparsers.add_parser('serve', help='start the server')
parser_server.add_argument('--config', help='path to configuration file')
parser_server.set_defaults(func=server)
parser_initdb = subparsers.add_parser('initdb', help='initialize data with table structure and seed data')
parser_initdb.add_argument('--config', help='path to configuration file')
parser_initdb.add_argument('--create-superuser', default=False,
action='store_true', help='create a superuser account')
parser_initdb.set_defaults(func=initdb)
args = parser.parse_args()
if hasattr(args, 'func'):
args.func(args)
else:
parser.print_help()
if __name__ == "__main__":
main()
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 Tim Hughes <[email protected]>
# Chase Seibert https://chase-seibert.github.io
# based on https://chase-seibert.github.io/blog/2014/03/21/python-multilevel-argparse.html
"""
"""
import sys
import argparse
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Cli:
def __init__(self):
parser = argparse.ArgumentParser()
parser.add_argument('command', help='Subcommand to run')
# parse_args defaults to [1:] for args, but you need to
# exclude the rest of the args too, or validation will fail
args = parser.parse_args(sys.argv[1:2])
if not hasattr(self, args.command):
printr('Unrecognized command')
parser.print_help()
exit(1)
# use dispatch pattern to invoke method with same name
getattr(self, args.command)()
def server(self):
parser = argparse.ArgumentParser(description='start the server')
parser.add_argument('--config', help='path to configuration file')
args = parser.parse_args(sys.argv[2:])
try:
logger.info(f"Running server {args}")
# start server here
pass
except KeyboardInterrupt:
logger.info("Exiting on KeyboardInterrupt")
except Exception as exc:
logger.info(f"Exiting on unknown error {exc}")
def initdb(self, args):
parser = argparse.ArgumentParser(
description='initialize data with table structure and seed data')
parser.add_argument('--config', help='path to configuration file')
parser.add_argument('--create-superuser', default=False,
action='store_true', help='create a superuser account')
logger.info(f"Initializing Database {args}")
# run initialize database code here
pass
if __name__ == "__main__":
Cli()
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 Tim Hughes <[email protected]>
#
# Distributed under terms of the MIT license.
"""
"""
import argparse
import logging
import sys
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Cli:
def __init__(self):
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
parser_server = subparsers.add_parser('serve', help='start the server')
parser_server.add_argument('--config', help='path to configuration file')
parser_server.set_defaults(func=self.server)
parser_initdb = subparsers.add_parser('initdb',
help='initialize data with table structure and seed data')
parser_initdb.add_argument('--config', help='path to configuration file')
parser_initdb.add_argument('--create-superuser', default=False,
action='store_true', help='create a superuser account')
parser_initdb.set_defaults(func=self.initdb)
args = parser.parse_args()
if hasattr(args, 'func'):
args.func(args)
else:
parser.print_help()
def server(self, args):
try:
logger.info(f"Running server {args}")
# start server here
pass
except KeyboardInterrupt:
logger.info("Exiting on KeyboardInterrupt")
except Exception as exc:
logger.info(f"Exiting on unknown error {exc}")
def initdb(self, args):
logger.info(f"Initializing Database {args}")
# run initialize database code here
pass
if __name__ == "__main__":
Cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment