[英]How can I exit a Python3 script after 5 minutes
I have a script that was copying data from SD card. 我有一个脚本正在从SD卡复制数据。 Due to the huge amount of files/filesize, this might take a longer period of time than expected.
由于大量的文件/文件大小,这可能需要比预期更长的时间。 I would like to exit this script after 5 minutes.
我想在5分钟后退出此脚本。 How can I do so?
我该怎么办?
It's hard to verify that this will work without any example code, but you could try something like this, using the signal module : 很难验证如果没有任何示例代码,它是否可以工作,但是您可以使用signal模块尝试这样的事情:
At the beginning of your code, define a handler for the alarm signal. 在代码的开头,定义警报信号的处理程序。
import signal
def handler(signum, frame):
print 'Times up! Exiting..."
exit(0)
Before you start the long process, add a line like this to your code: 在开始漫长的过程之前,请在代码中添加如下一行:
#Install signal handler
signal.signal(signal.SIGALRM, handler)
#Set alarm for 5 minutes
signal.alarm(300)
In 5 minutes, your program will receive the alarm signal, which will call the handler, which will exit. 在5分钟内,您的程序将收到警报信号,该警报信号将调用处理程序,然后退出。 You can also do other things in the handler if you want.
如果需要,您还可以在处理程序中执行其他操作。
Here, the threading module comes in handily: 在这里,线程模块可以方便地使用:
import threading
def eternity(): # your method goes here
while True:
pass
t=threading.Thread(target=eternity) # create a thread running your function
t.start() # let it run using start (not run!)
t.join(3) # join it, with your timeout in seconds
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.