如何在 5 分钟后退出 Python3 脚本 [英] How can I exit a Python3 script after 5 minutes
问题描述
我有一个从 SD 卡复制数据的脚本.由于大量文件/文件大小,这可能需要比预期更长的时间.我想在 5 分钟后退出这个脚本.我该怎么做?
I have a script that was copying data from SD card. 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. 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:
在代码的开头,为警报信号定义一个处理程序.
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)
5 分钟后,您的程序将收到警报信号,该信号将调用处理程序,该处理程序将退出.如果需要,您还可以在处理程序中执行其他操作.
In 5 minutes, your program will receive the alarm signal, which will call the handler, which will exit. You can also do other things in the handler if you want.
这篇关于如何在 5 分钟后退出 Python3 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!