jw-python/tools/python/jwutils/Cmds.py
Jan Lindemann fd125f07fe Add class Cmds
run_sub_commands() was the only way to access subcommands up to now,
Cmds.run() adds another interface, an object as a place to add
customizations affecting all commands, e.g. global command line
options.

Signed-off-by: Jan Lindemann <jan@janware.com>
2018-12-11 14:10:01 +01:00

44 lines
1.6 KiB
Python

import os
import sys
import argparse
import Object
import jwutils.log
import importlib
import inspect
import re
class Cmds(Object.Object): # export
def __init__(self, description = '', filter = '^Cmd.*', modules=None):
self.__description = description
self.__filter = filter
self.__modules = modules
self.__parser = argparse.ArgumentParser(usage=os.path.basename(sys.argv[0]) + ' [command] [options]',
formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=self.__description)
self.__parser.add_argument('--log-flags', help='Log flags', default='stderr,position,prio,color')
self.__parser.add_argument('--log-level', help='Log level', default=jwutils.log.NOTICE)
subparsers = self.__parser.add_subparsers(title='Available commands', metavar='')
if self.__modules == None:
self.__modules = [ '__main__' ]
for m in self.__modules:
if m != '__main__':
importlib.import_module(m)
for name, c in inspect.getmembers(sys.modules[m], inspect.isclass):
if not re.match(self.__filter, name):
continue
if inspect.isabstract(c):
continue
c().add_parser(subparsers)
def parser():
return self.__parser
def run(self):
args = self.__parser.parse_args()
jwutils.log.set_level(args.log_level)
jwutils.log.set_flags(args.log_flags)
args.func(args)
def run_sub_commands(description = '', filter = '^Cmd.*', modules=None): # export
cmds = Cmds(description, filter, modules)
cmds.run()