Skip to content

Instantly share code, notes, and snippets.

@ivanistheone
Last active May 26, 2017
Embed
What would you like to do?
Proof of concept for combining command line arguments.

Combining argparse parsers

This is a proof of concept for a command line interface (CLI) that is subclassable. TO use, create an instance of the class (or subclass) and call it's main method.

The only tricky part is that subclasses need to pass add_parser_help=False when calling the BaseCLI's __init__ method.

Using base.py by itself

> ./base.py -h
usage: base.py [-h] [--token TOKEN]

Base class CLI.

optional arguments:
  -h, --help     show this help message and exit
  --token TOKEN  Token from the content server

Example usage

> ./base.py --token THISISATOKEN
In BaseCLI's main method. args= Namespace(token='THISISATOKEN')
In BaseCLI's importchannel command.
args: Namespace(token='THISISATOKEN')

Using subclass.py

> ./subclass.py -h
usage: subclass.py [-h] [--token TOKEN] [--step STEP]

Subclass CLI demo

optional arguments:
  -h, --help     show this help message and exit
  --token TOKEN  Token from the content server
  --step STEP    An argument specific to the SubclassCLI

Example usage:

> ./subclass.py --token THISISANOTERTOKEN --step 3
In SubclassCLI's main method. args= Namespace(step='3', token='THISISANOTERTOKEN')
In BaseCLI's importchannel command.
args: Namespace(step='3', token='THISISANOTERTOKEN')
#!/usr/bin/env python3
import argparse
class BaseCLI(object):
"""
A base class for creating CLI modules.
"""
def __init__(self, *args, add_parser_help=True, **kwargs):
"""
Need to pass in `add_parser_help=False` when subclassing.
"""
self.arg_parser = argparse.ArgumentParser(description="Base class CLI.",
add_help=add_parser_help)
self.arg_parser.add_argument('--token', help='Token from the content server')
def importchannel(self, args):
print('In BaseCLI\'s importchannel command.')
print('args:', args)
def main(self):
args = self.arg_parser.parse_args()
print('In BaseCLI\'s main method. args=', args)
self.importchannel(args)
if __name__ == '__main__':
base_cli = BaseCLI()
base_cli.main()
#!/usr/bin/env python3
import argparse
from base import BaseCLI
class SubclassCLI(BaseCLI):
"""
A subclass of the CLI module.
Inherits all the command line arguments from BaseCLI and also adds an
additioal command line argument --step
"""
def __init__(self, *args, **kwargs):
super(SubclassCLI, self).__init__(*args, add_parser_help=False, **kwargs)
self.arg_parser = argparse.ArgumentParser(description="Subclass CLI demo",
parents=[self.arg_parser])
self.arg_parser.add_argument('--step', help='An argument specific to the SubclassCLI')
def main(self):
args = self.arg_parser.parse_args()
print('In SubclassCLI\'s main method. args=', args)
self.importchannel(args)
if __name__ == '__main__':
subclass_cli = SubclassCLI()
subclass_cli.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment