make line-splitting optional in call_and_capture
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Tue, 12 Jan 2016 12:28:07 +0000 (13:28 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Tue, 12 Jan 2016 12:28:07 +0000 (13:28 +0100)
call_helpers.py

index 986066d..6356d4e 100644 (file)
@@ -10,7 +10,8 @@ Stay python2 compatible --> no timeouts
 from subprocess import Popen, PIPE
 
 
-def call_and_capture(command, stdin_data=None, *args, **kwargs):
+def call_and_capture(command, stdin_data=None, split_lines=True,
+                     *args, **kwargs):
     """ call command, captures stdout, stderr and return code, return when done
 
     Use only for commands with little output since all output has to be
@@ -28,12 +29,16 @@ def call_and_capture(command, stdin_data=None, *args, **kwargs):
 
     :param command: forwarded as first arg to Popen constructor
     :param str stdin_data: forwarded to stdin of process through communicate
+    :param bool split_lines: True (default) to split output line-wise and
+                             return list of strings; False --> return single
+                             string for out and one for err
     :param args: forwarded to Popen constructor
     :param kwargs: forwarded to Popen constructor
     :returns: (return_code, stdout, stderr); stdout and stderr are lists of
         text lines (without terminating newlines); if universal_newlines is
         True (default), the lines are of type str, otherwise they are non-
-        unicode text (type str in py2, bytes in py3)
+        unicode text (type str in py2, bytes in py3). If split_lines is False
+        (not default), then stdout and stderr are single multi-line strings
 
     :raise: OSError (e.g., if command does not exist), ValueError if args are
             invalid; no :py:class:`subprocess.CalledProcessError` nor
@@ -53,4 +58,8 @@ def call_and_capture(command, stdin_data=None, *args, **kwargs):
     stdout_data, stderr_data = proc.communicate(stdin_data)
 
     # return
-    return proc.returncode, stdout_data.splitlines(), stderr_data.splitlines()
+    if split_lines:
+        return proc.returncode, stdout_data.splitlines(), \
+            stderr_data.splitlines()
+    else:
+        return proc.returncode, stdout_data, stderr_data