Last active
March 22, 2018 20:20
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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