mirror of
ssh://git.janware.com/srv/git/janware/proj/jw-python
synced 2026-01-15 18:03:31 +01:00
44 lines
1.6 KiB
Python
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()
|