Skip to content

Instantly share code, notes, and snippets.

@conrad784
Last active March 22, 2018 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conrad784/373a0bad680ae65cf25dae2cf4bb88ed to your computer and use it in GitHub Desktop.
Save conrad784/373a0bad680ae65cf25dae2cf4bb88ed to your computer and use it in GitHub Desktop.
function to get stderr in other variable as stdout and also possible to print the output in real-time
def subprocess_get_all_outputs(cmd, shell=True, print_stdout=True, print_stderr=True):
"""
behaves like a subprocess.check_output() where you can get print output
of stdout and stderr and both also in variables
"""
import subprocess
out = b''
err = b''
p = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
stdout_line = p.stdout.readline()
out += stdout_line
stderr_line = p.stderr.readline()
err += stderr_line
if stdout_line and print_stdout:
print(stderr_line.decode('utf8').strip())
if stderr_line and print_stderr:
print(stderr_line.decode('utf8').strip())
if stdout_line == b'' and stderr_line == b'' and p.poll() is not None:
break
rc = p.poll()
return rc, out, err
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment