Skip to content

Instantly share code, notes, and snippets.

@thenger
Created April 29, 2020 09:38
Show Gist options
  • Save thenger/4b1754b19b6ce6d70904f01a2dc1b955 to your computer and use it in GitHub Desktop.
Save thenger/4b1754b19b6ce6d70904f01a2dc1b955 to your computer and use it in GitHub Desktop.
Python display subprocess stdout in real time
# Redirect stderr and stdout of a subprocess to the python ones
def exec_cmd_with_output(cmd):
stdoutlines = []
a_process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while a_process.poll() is None:
line = a_process.stdout.readline()
stdoutlines.append(line)
sys.stdout.write(line.decode(sys.stdout.encoding))
return a_process.returncode, stdoutlines
def exec_cmd_with_output_with_verbosity(cmd, verbos = 0):
#log_debug("Launching command: '%s'" % cmd)
if verbos < 0:
fd_devnull = open(os.devnull, 'w')
a_process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
a_process.wait()
stdoutlines = None
fd_devnull.close()
else:
stdoutlines = []
a_process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while a_process.poll() is None:
line = a_process.stdout.readline()
stdoutlines.append(line)
sys.stdout.write(line.decode(sys.stdout.encoding))
return a_process.returncode, stdoutlines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment