0

I want to monitor the stdout of a program and whenever it prints something into stdout, I want to get a callback in python to process the gathered data.

The program I want to monitor is not written in python, but behaves similar to this dummy_script.py:

import datetime
import random
import time

i = 0
while True:
    line = f"{datetime.datetime.now()} {i}"
    print(line)
    i += 1
    time.sleep(random.uniform(0, 1))

For the main python script I tried something like this:

from threading import Thread
import os


def do_stuff():
    command = f"python3 dummy_script.py"
    os.system(command)


thread = Thread(target=do_stuff)
thread.daemon = True
thread.start()

So is there a way to create a callback when a new line is printed to stdout?

  • 1
    Like this maybe https://stackoverflow.com/a/2813530/2836621 – Mark Setchell Jan 07 '23 at 13:27
  • [`os.system`](https://docs.python.org/3/library/os.html#os.system) is blocking, you should use a non-blocking call instead, so `subprocess.Popen` like in the answer from Mark. – Lenormju Jan 09 '23 at 07:27

0 Answers0