Python中如何在一段时间后停止程序

写了一个分析大数据的python程序,由于要分析的数据量可能会很大,有时运行的时间会很长。服务器上的设置是有进程运行超过10分钟会自动Kill该进程,所以我希望我的程序在运行到9分50秒的时候可以Print一条警报“Warning: Timeout”。

请问需要如何修改程序才能达到此目的,能否只在程序头尾添加语句而不改变程序内部结构?

以下面一个无线循环的Loop为例,如何修改能让它在10秒后打印一条警报?

def func(a,b):
while True:
a=a+b
print a
func(1,2)

用到threading的Timer,也类似单片机那样子,在中断程序中再重置定时器,设置中断,python实例代码如下:

import threading

import time

def change_user():

    print('这是中断,切换账号')

    t = threading.Timer(3, change_user)

    t.start()

#每过3秒切换一次账号

t = threading.Timer(3, change_user)

t.start()

while True:

    print('我在爬数据')

    time.sleep(1)

扩展资料

有时当一个条件成立的情况下,需要终止程序,可以使用sys.exit()退出程序。sys.exit()会引发一个异常:

1、如果这个异常没有被捕获,那么python编译器将会退出,后面的程序将不会执行。

2、如果这个异常被捕获(try...except...finally),捕获这个异常可以做一些额外的清理工作,后面的程序还会继续执行。

注:0为正常退出,其他数值(1-127)为不正常,可抛异常事件供捕获。另一种终止程序的方法os._exit()

一般情况下使用sys.exit()即可,一般在fork出来的子进程中使用os._exit()

采用sys.exit(0)正常终止程序,程序终止后shell运行不受影响。

采用os._exit(0)关闭整个shell,调用sys._exit(0)后整个shell都重启了(RESTART Shell)。

温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2017-11-25
#python 2.7
import time #导入 time类
start=time.clock()
def func(a,b):
while True:
end=time.clock ()
if int(end-start)==10:
print('Warning: Timeout!!'*5)
break
a=a+b

print a
func(1,2)

主要思路:开始时间-当前时间=10则停止运行并输出时间到了(注意缩进)追问

多谢。方法是很简洁,但是有一个小问题啊。
我给的这个例子里func的功能很简单,只有a=a+b这样简单的计算。如果function里的计算量会很大。如果只在循环开头判定时间的话,如果在某次循环内就达到时间上线的话,来不及进行下一次循环判定时间就会被服务器Kill了,这样会答应不了警报信息哦。请问有没有办法实时监控时间呢?比如每秒判定一次时间,类似于独立于主程序之外再创建一个监控时间的进程。有办法实现吗。。。

追答

你说的我考虑过,但是情况都一样的,怎么样都要消耗资源,只要你去计算时间。
有比较好的方法就是:再建立一个进程,单独的在主程序运行时他运行,然后他只做计时,10秒后在print。但这样的方法比较复杂。
另外:如果从解决问题角度出发的话,有很多的办法啊,可以同时执行2个程序,一个是主程序,一个是只做计时等待警告程序,可以用批处理。
python warn.py
python main.py
做成bat就行了。相对而言等待程序消耗资源很少。也可以直接用批处理去等待,效率更高

本回答被提问者和网友采纳
第2个回答  2013-04-04
建议你另起一个timer的线程,计算时间并输出警告。送你一段定时器timer的代码。
使用前先做一个简单试验:
import threading def sayhello():
print "hello world"
global t #Notice: use global variable!
t = threading.Timer(5.0, sayhello)
t.start()

t = threading.Timer(5.0, sayhello)
t.start()

运行结果如下
>python hello.py
hello world
hello world
hello world
下面是定时器类的实现:
class Timer(threading.Thread): """
very simple but useless timer.
"""
def __init__(self, seconds):
self.runTime = seconds
threading.Thread.__init__(self)
def run(self):
time.sleep(self.runTime)
print "Buzzzz!! Time's up!"

class CountDownTimer(Timer):
"""
a timer that can counts down the seconds.
"""
def run(self):
counter = self.runTime
for sec in range(self.runTime):
print counter
time.sleep(1.0)
counter -= 1
print "Done"

class CountDownExec(CountDownTimer):
"""
a timer that execute an action at the end of the timer run.
"""
def __init__(self, seconds, action, args=[]):
self.args = args
self.action = action
CountDownTimer.__init__(self, seconds)
def run(self):
CountDownTimer.run(self)
self.action(self.args)

def myAction(args=[]):
print "Performing my action with args:"
print args

if __name__ == "__main__": t = CountDownExec(3, myAction, ["hello", "world"])
t.start()追问

请问我的那段代码应该放在什么位置?我对编程还是门外汉。。。。

第3个回答  2018-08-13
把程序单开成一个线程或者进程,最好开进程,python的多线程。。。不太好用,然后用time模块等待几秒,之后直接结束进程就行。
第4个回答  2013-04-04
用装饰器能做到。不过有点技巧
相似回答