Last active
January 31, 2024 16:56
-
-
Save meherhendi/5e0ecbc04e58602fede6699ee5d4e455 to your computer and use it in GitHub Desktop.
Python non blocking subprocess output
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
# this function allows outputting the subprocess output to the console without blocking the execution of the program by | |
# assigning the printing function to a thread | |
def run_command(self, command): | |
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
def readstdout(): | |
for line in p.stdout: | |
print(line.strip()) | |
# Prefer using readstdout without parentheses (readstdout and not readstdout()). In the second case, | |
# readstdout() is immediately executed, and its result is passed to the thread before the thread is created. | |
thread = Thread(target=readstdout) | |
# Start the threads to capture and print the subprocess output | |
thread.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment