jw-python/tools/python/jwutils/Cmds.py
Jan Lindemann 6dd594d47b Fix multiple Python 3 compatibility issues
Changes in Python 3 that made the code choke:

  o basestring is merged into str
  o print() needs parentesis
  o Class inheritance syntax changed
  o Abstract baseclass (ABCMeta) syntax changed
  o map.iteritems() is replaced by map.items()
  o Inconsistent use of tabs and spaces are no longer tolerated

Signed-off-by: Jan Lindemann <jan@janware.com>
2019-03-10 16:38:59 +01:00

44 lines
1.6 KiB
Python

import os
import sys
import argparse
import jwutils
import importlib
import inspect
import re
import pickle
class Cmds: # 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()