Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ekawahyu/78505cfbbfaeaded6e06c973606caf22 to your computer and use it in GitHub Desktop.
Save ekawahyu/78505cfbbfaeaded6e06c973606caf22 to your computer and use it in GitHub Desktop.
Python display subprocess stdout in real time
import os
import shlex
import subprocess
# 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)
for line in a_process.stdout:
stdoutlines.append(line.decode().rstrip())
print(line.decode().rstrip())
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)
for line in a_process.stdout:
stdoutlines.append(line.decode().rstrip())
print(line.decode().rstrip())
return a_process.returncode, stdoutlines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment