mirror of
ssh://git.janware.com/srv/git/janware/proj/jw-python
synced 2026-01-15 01:52:56 +01:00
Add Cmd.py
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
15abefdec7
commit
22cabb4eac
1 changed files with 48 additions and 0 deletions
48
tools/python/jwutils/Cmd.py
Normal file
48
tools/python/jwutils/Cmd.py
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
from abc import ABCMeta, abstractmethod
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import inspect
|
||||||
|
import re
|
||||||
|
|
||||||
|
import Object
|
||||||
|
|
||||||
|
class Cmd(Object.Object): # export
|
||||||
|
|
||||||
|
__metaclass__=ABCMeta
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def run(self, args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __init__(self, name, help):
|
||||||
|
self.name = name
|
||||||
|
self.help = help
|
||||||
|
|
||||||
|
def _run(self, args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def add_parser(self, parsers):
|
||||||
|
r = parsers.add_parser(self.name, help=self.help,
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||||
|
r.set_defaults(func=self.run)
|
||||||
|
return r
|
||||||
|
|
||||||
|
def run_sub_commands(description = '', prefix = 'Cmd'): # export
|
||||||
|
|
||||||
|
classes = inspect.getmembers(sys.modules["__main__"], inspect.isclass)
|
||||||
|
parser = argparse.ArgumentParser(usage=os.path.basename(sys.argv[0]) + ' [command] [options]',
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=description)
|
||||||
|
parser.add_argument('--log-level', help='Log level', default='notice')
|
||||||
|
subparsers = parser.add_subparsers(title='Available commands', metavar='')
|
||||||
|
|
||||||
|
for (name, cls) in classes:
|
||||||
|
if not re.match('^Cmd.', name):
|
||||||
|
continue
|
||||||
|
if inspect.isabstract(cls):
|
||||||
|
continue
|
||||||
|
cls().add_parser(subparsers)
|
||||||
|
|
||||||
|
args=parser.parse_args()
|
||||||
|
jwutils.log.set_level(args.log_level)
|
||||||
|
args.func(args)
|
||||||
Loading…
Add table
Add a link
Reference in a new issue