繁体   English   中英

如果时间过长,中断 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.")

而不是使用subprocess.run ,尝试os.system并使用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时,它会阻塞,直到达到超时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM