Skip to content

Instantly share code, notes, and snippets.

@meherhendi
Last active January 31, 2024 16:56
Show Gist options
  • Save meherhendi/5e0ecbc04e58602fede6699ee5d4e455 to your computer and use it in GitHub Desktop.
Save meherhendi/5e0ecbc04e58602fede6699ee5d4e455 to your computer and use it in GitHub Desktop.
Python non blocking subprocess output
# 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