写了一个分析大数据的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)。
多谢。方法是很简洁,但是有一个小问题啊。
我给的这个例子里func的功能很简单,只有a=a+b这样简单的计算。如果function里的计算量会很大。如果只在循环开头判定时间的话,如果在某次循环内就达到时间上线的话,来不及进行下一次循环判定时间就会被服务器Kill了,这样会答应不了警报信息哦。请问有没有办法实时监控时间呢?比如每秒判定一次时间,类似于独立于主程序之外再创建一个监控时间的进程。有办法实现吗。。。
你说的我考虑过,但是情况都一样的,怎么样都要消耗资源,只要你去计算时间。
有比较好的方法就是:再建立一个进程,单独的在主程序运行时他运行,然后他只做计时,10秒后在print。但这样的方法比较复杂。
另外:如果从解决问题角度出发的话,有很多的办法啊,可以同时执行2个程序,一个是主程序,一个是只做计时等待警告程序,可以用批处理。
python warn.py
python main.py
做成bat就行了。相对而言等待程序消耗资源很少。也可以直接用批处理去等待,效率更高
请问我的那段代码应该放在什么位置?我对编程还是门外汉。。。。