python - 如果花费太长时间,则在 python 中中断 shell 进程
问题描述
我正在编写脚本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
选项,而不是 using :
# 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
,它会阻塞,直到达到超时。
推荐阅读
- azure-devops - Azure DevOps:将文件复制到任务失败,并显示“未找到 SourceFolder:D:\a\1\s\$(Build.SourceDirectory)”
- javascript - 如何将 div 放在粘性导航栏下?
- javascript - 你会如何推荐我自动化网站数据输入?
- sql - 选择表中可能存在或不存在的列名,并获取空值而不是错误
- angular - 反应形式中的形式
- regex - 使用带有环境变量的 sed 替换文件中的文本
- mongodb - 我可以在 mongodb 的 $push 中使用现有的文档字段值吗?我尝试了以下方法,它不起作用
- java - 用逗号分割字符串,但不包括任何数字的双引号,而只包括字符串
- shell - 如何将 Jenkins 构建中的“params”对象回显到 shell 中的 sed 指令中?
- javascript - highcharts $_post['value'] 不打印图表值