如果花费的时间太长,请中断 python 中的 shell 进程

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

我正在 python 编写脚本。 我需要写入磁盘和 运行 一些 shell 脚本。 但是,根据输入的不同,这些可能需要很长时间,如果时间太长我想杀死它们。 我想要这样的东西:

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.")

不要使用 os.system,请尝试 subprocess.run 并使用 timeout 选项:

# 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")

当您 运行 python monitor.py 时,它会阻塞直到达到超时。