在执行shell / python脚本时定义超时

时间:2014-09-02 05:23:27

标签: python bash shell

我遇到了从shell脚本调用我的python脚本的问题。由于某些问题,执行一个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 个答案:

答案 0 :(得分:1)

使用timeout

timeout --kill-after=305 300 script2.py

答案 1 :(得分: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 
相关问题