shell_command: refactor output parsing

Separate output by line, and execute the output callback once per line.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
This commit is contained in:
Arksine 2020-11-20 06:51:28 -05:00
parent 116c1e9f29
commit 093b8c14d6
1 changed files with 9 additions and 13 deletions

View File

@ -12,7 +12,7 @@ from tornado import gen
from tornado.ioloop import IOLoop from tornado.ioloop import IOLoop
class ShellCommand: class ShellCommand:
def __init__(self, cmd, callback=None): def __init__(self, cmd, callback):
self.io_loop = IOLoop.current() self.io_loop = IOLoop.current()
self.name = cmd self.name = cmd
self.output_cb = callback self.output_cb = callback
@ -29,17 +29,13 @@ class ShellCommand:
except Exception: except Exception:
return return
data = self.partial_output + data data = self.partial_output + data
if b'\n' not in data: lines = data.split(b'\n')
self.partial_output = data self.partial_output = lines.pop()
return for line in lines:
elif data[-1] != b'\n': try:
split = data.rfind(b'\n') + 1 self.output_cb(line)
self.partial_output = data[split:] except Exception:
data = data[:split] logging.exception("Error writing command output")
try:
self.output_cb(data)
except Exception:
logging.exception("Error writing command output")
def cancel(self): def cancel(self):
self.cancelled = True self.cancelled = True
@ -108,7 +104,7 @@ class ShellCommand:
class ShellCommandFactory: class ShellCommandFactory:
def build_shell_command(self, cmd, callback): def build_shell_command(self, cmd, callback=None):
return ShellCommand(cmd, callback) return ShellCommand(cmd, callback)
def load_plugin(config): def load_plugin(config):