Alex Coleman
Alex Coleman

Reputation: 647

Interrupt shell process in python if it's taking too long

I'm scripting in python. I need to write to disk, and run some shell scripts. However, depending on the the input, these may take a long time, and I want to kill them if they take too long. I want something like:

def run_once(input_text):
    with open("temp.file", "w") as f:
        f.write(input_text)
    os.system("./synthesize.sh temp.tsl")

for single in many:
    if(takes_more_than_60_seconds(run_once(input_text)):
        kill(process)
        print("Process killed since it took too long. Moving to the next job.")

Upvotes: 0

Views: 245

Answers (1)

dwhswenson
dwhswenson

Reputation: 533

Instead of using os.system, try subprocess.run and use the timeout option:

# file: sleepy.py
import time
time.sleep(10)
# file: monitor.py
import subprocess
import shlex

try:
    subprocess.run(shlex.split("python sleepy.py"), timeout=5)
except subprocess.TimeoutExpired:
    print("Timed out")

When you run python monitor.py, it blocks until the timeout is reached.

Upvotes: 1

Related Questions