support basic internal pipeline (cli_entry)
import sys
import importlib
import pkgutil
+import itertools
+from io import StringIO
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from kgtk import cli
@@ -13,6 +15,9 @@ handlers = [x.name for x in pkgutil.iter_modules(cli.__path__)
if not x.name.startswith('__')]
+pipe_delimiter = '/'
+
+
class KGTKArgumentParser(ArgumentParser):
def __init__(self, *args, **kwargs):
if not kwargs.get('formatter_class'):
@@ -36,7 +41,7 @@ def cli_entry(*args):
sub_parsers = parser.add_subparsers(
metavar='command',
- dest='cmd',
+ dest='cmd'
)
sub_parsers.required = True
@@ -51,13 +56,29 @@ def cli_entry(*args):
args = tuple(sys.argv)
if len(args) == 1:
args = args + ('-h',)
- args = parser.parse_args(args[1:])
+ args = args[1:]
+
+ stdout_ = sys.stdout
+ last_stdout = StringIO()
+ ret_code = 0
- # run
+ for cmd_args in [tuple(y) for x, y in itertools.groupby(args, lambda a: a == pipe_delimiter) if not x]:
+ # parse command and options
+ args = parser.parse_args(cmd_args)
+
+ # load module
func = None
if args.cmd:
mod = importlib.import_module('.{}'.format(args.cmd), 'kgtk.cli')
func = mod.run
kwargs = vars(args)
del kwargs['cmd']
- return kgtk_exception_handler(func, **kwargs)
+
+ # run module
+ last_stdout.close(); last_stdout = StringIO()
+ ret_code = kgtk_exception_handler(func, **kwargs)
+ sys.stdin.close(); sys.stdin = StringIO(last_stdout.getvalue())
+
+ stdout_.write(last_stdout.getvalue())
+ last_stdout.close(); sys.stdin.close()
+ return ret_code
