Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

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.")
question from:https://stackoverflow.com/questions/65926239/interrupt-shell-process-in-python-if-its-taking-too-long

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...