From 30c539f1f26a390b44038e2b5137638e0801b8a2 Mon Sep 17 00:00:00 2001 From: Tobias Witek Date: Sun, 23 Feb 2020 13:44:49 +0100 Subject: [PATCH] [util/cli] Add option to ignore return codes Add an option that ignores the return code of an execute, instead of throwing an error (which sometimes causes ugly try/except blocks in client code) --- tests/util/test_cli.py | 6 ++++++ util/cli.py | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/util/test_cli.py b/tests/util/test_cli.py index 30fccee..5e2de98 100644 --- a/tests/util/test_cli.py +++ b/tests/util/test_cli.py @@ -26,6 +26,12 @@ class cli(unittest.TestCase): with self.assertRaises(RuntimeError): util.cli.execute('cat {}'.format(self.nonExistentCommand)) + def test_command_exit_code_no_error(self): + try: + util.cli.execute('cat {}'.format(self.nonExistentCommand), ignore_errors=True) + except Exception: + self.fail('exception was thrown') + def test_async(self): rv = util.cli.execute(self.validCommand, wait=False) self.assertEqual('', rv) diff --git a/util/cli.py b/util/cli.py index 4e7b74a..e16ed6e 100644 --- a/util/cli.py +++ b/util/cli.py @@ -2,7 +2,7 @@ import shlex import subprocess import logging -def execute(cmd, wait=True): +def execute(cmd, wait=True, ignore_errors=False): args = shlex.split(cmd) logging.debug(cmd) try: @@ -12,7 +12,7 @@ def execute(cmd, wait=True): if wait: out, _ = proc.communicate() - if proc.returncode != 0: + if proc.returncode != 0 and not ignore_errors: raise RuntimeError('{} exited with {}'.format(cmd, proc.returncode)) return out.decode('utf-8') return ''