为Shell/Python脚本定义执行超时
我在运行我的Python脚本时遇到了一些问题,这些脚本是从Shell脚本中调用的。由于某些原因,有一个Python脚本的执行时间非常长。现在,我想给我的Python脚本设置一个超时,如果它运行超过“n”分钟,就应该终止当前脚本的执行,接着执行下一个脚本。
MasterScript.sh file contain multiple Python scripts like
script1.py
script2.py - this script is taking more time.. if it more then 5 minute, script execution should terminiate and move to next one.
script3.py
2 个回答
3
使用 timeout
命令
timeout --kill-after=305 300 script2.py
1
假设这是你的 test1.py 脚本:
#! /usr/bin/python
import time
import sys
sys.stdout.write("in test1\n")
time.sleep(20)
sys.stdout.write("Done")
这个脚本应该在打印“完成”之前暂停20秒,但我们会从我们的 shell 脚本中终止它。
接下来是一个在 test1.py 之后运行的 test.py 脚本。
#! /usr/bin/python
import sys
sys.stdout.write("In test2\n")
sys.stdout.write("Done")
现在是你的 shell 脚本,它会运行这两个脚本:
#! /bin/bash
timeout 10 python test1.py
python test2.py