I am running a program from a python script (currently with os.system
). However, sometimes the program hangs at a point and I would like to kill it if nothing is written to stdout or stderr after a certain time interval. A simple timeout on the program won't work, because this code typically runs for a very long time (many hours to days), and sometimes it hangs before it still has a long way to go.
It seems that subprocess.Popen
is the way to go, but I haven't found a good example on how to do this. I also wanted to write the stdout/stderr to a file.
Based on some examples I was thinking about something like this:
p = Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None)
while True:
line = p.stdout.readline()
outfile.write(line)
# save current time or something, compare to time of
# previous loop, if larger than timeout, kill process
But I'm not sure how to implement the time loop, and how to make sure that the while
doesn't run forever when the process eventually terminates on its own (and doesn't hang). Any pointers would be much appreciated.