From 9d4936b596ea23ac04fd5eb2cd47664dc4a4fbcb Mon Sep 17 00:00:00 2001 From: Tobias Witek Date: Sat, 8 Feb 2020 13:39:35 +0100 Subject: [PATCH] [util/cli] Add new CLI utilities For now, this just allows executing commands --- tests/util/test_cli.py | 33 +++++++++++++++++++++++++++++++++ util/cli.py | 20 ++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 tests/util/test_cli.py create mode 100644 util/cli.py diff --git a/tests/util/test_cli.py b/tests/util/test_cli.py new file mode 100644 index 0000000..30fccee --- /dev/null +++ b/tests/util/test_cli.py @@ -0,0 +1,33 @@ +import unittest + +import util.cli + +class cli(unittest.TestCase): + def setUp(self): + self.nonExistentCommand = 'i-do-not-exist' + self.validCommand = 'echo test' + self.validCommandOutput = 'test\n' + self.utfCommand = 'echo ÖPmŧß' + self.utfCommandOutput = 'ÖPmŧß\n' + + def test_valid_command(self): + rv = util.cli.execute(self.validCommand) + self.assertEqual(self.validCommandOutput, rv) + + def test_utf_command(self): + rv = util.cli.execute(self.utfCommand) + self.assertEqual(self.utfCommandOutput, rv) + + def test_invalid_command(self): + with self.assertRaises(RuntimeError): + util.cli.execute(self.nonExistentCommand) + + def test_command_exit_code(self): + with self.assertRaises(RuntimeError): + util.cli.execute('cat {}'.format(self.nonExistentCommand)) + + def test_async(self): + rv = util.cli.execute(self.validCommand, wait=False) + self.assertEqual('', rv) + +# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 diff --git a/util/cli.py b/util/cli.py new file mode 100644 index 0000000..4e7b74a --- /dev/null +++ b/util/cli.py @@ -0,0 +1,20 @@ +import shlex +import subprocess +import logging + +def execute(cmd, wait=True): + args = shlex.split(cmd) + logging.debug(cmd) + try: + proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + except FileNotFoundError as e: + raise RuntimeError('{} not found'.format(cmd)) + + if wait: + out, _ = proc.communicate() + if proc.returncode != 0: + raise RuntimeError('{} exited with {}'.format(cmd, proc.returncode)) + return out.decode('utf-8') + return '' + +# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4