Forked from thenger/subprocess_stdout_instantly.py
Last active
October 7, 2024 04:52
-
-
Save ekawahyu/78505cfbbfaeaded6e06c973606caf22 to your computer and use it in GitHub Desktop.
Python display subprocess stdout in real time
This file contains 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
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