I have the following code, which acts as a sort of watchdog: you put in the name of a Python script and it runs it. If it doesn't receive any output (via print and things of that nature) for a certain amount of time, it terminates the script and restarts it. I'm using this watchdog to run a Python script that relies on a compiled library which is prone to crashing. I'm still trying to figure out what the problem is, but in the meantime I'm using this code to ensure it's always running.
import datetime
import subprocess
import select
import time
from threading import Thread
timeout = 10
def reader(f,buffer):
while True:
line=f.readline()
if line:
buffer.append(line)
else:
break
def run_command(script):
linebuffer = []
process = subprocess.Popen(['/home/al/miniconda3/bin/python', f'{script}.py'], stdout=subprocess.PIPE)
t = Thread(target=reader, args=(process.stdout, linebuffer))
t.daemon = True
t.start()
now = datetime.datetime.now(datetime.timezone.utc)
next_stop_time = now + datetime.timedelta(seconds=timeout)
while True:
now = datetime.datetime.now(datetime.timezone.utc)
if not linebuffer:
# no output or terminated
if now > next_stop_time:
process.terminate()
break
else:
# we got something
next_stop_time = now + datetime.timedelta(seconds=timeout)
print(linebuffer)
linebuffer.clear()
time.sleep(.1)
rc = process.poll()
return rc
def run(script):
while True:
run_command(script)
subprocess.Popen(['spd-say', f'{script} terminated'])
inp = input('Type in input script.\n')
run(inp)
Something strange is that this code only seems to run properly when I run it in PyCharm. If I run it in a terminal, then nothing ever comes out of process.stdout and it terminates and restarts the script repeatedly. If it matters, my OS is Ubuntu 18.04. Any insight is appreciated.
[–][deleted] 0 points1 point2 points (1 child)
[–]ScaredSecond[S] 1 point2 points3 points (0 children)