from formatters import Printer from io import StringIO class BaseCommand(object): def __call__(self, *args, **kwargs): raise NotImplementedError( "BaseCommands must be callable and return a generator") class NoneCommand(BaseCommand): def __call__(self, *args, **kwargs): return [] class RawCommand(BaseCommand): """Fallback raw command that just invokes an existing Unix utility program with the builtin subprocess module. Each output object is just a tree node whose data is a simple string.""" def __init__(self, cmd, input_generator=[], args=tuple()): self.input_generator = input_generator self.cmd = cmd self.args = args def __call__(self, input_generator=[], *args, **kwargs): import subprocess try: p = subprocess.Popen((self.cmd,) + self.args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def output_generator(): input_str = b"" for line in input_generator: input_str += line outs, errs = p.communicate(input_str) if outs: yield outs return output_generator() except: import traceback traceback.print_exc() return [] registered_cmds = [] def register_cmd(cls): registered_cmds.append(cls.__name__) return cls