简体   繁体   English

5分钟后如何退出Python3脚本

[英]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.

相关问题 如何使用 python 每 60 分钟重复一次脚本 - How can I repat a script every 60 minutes with python Python,如何让我的程序在5分钟后自动退出? - In Python, how do I make my program automatically exit after 5 minutes? 如何从Python 3退出程序(不是python脚本)? - How can I exit a program (not python script) from Python 3? 我该如何在python中制作一个脚本,该脚本在yy天每隔xx分钟执行一次,并且在时间到期后关闭文件 - How can i make an script in python that executes every xx minutes for yy days and after the time expires it closes the file 如何使用python获取脚本退出状态? - how can i get script exit status with python? 如何让 python 脚本安全退出? - How can I have a python script safely exit itself? Python - 1秒后我无法退出GUI,当调用gtk.main()时它永远不会退出,我该如何退出? - Python - After 1 second i cant exit the GUI, when ever the gtk.main() is called it never exit, how can i exit? 每小时执行后如何让 python 脚本休眠 xx 分钟? - How to sleep python script for xx minutes after every hour execution? 如何在 conda env 中安排一个 python 脚本每 n 分钟运行一次? - How can I schedule a python script inside a conda env to run every n minutes? 从远程服务器(CentOS-7)退出后,`python3 manage.py runserver`将不起作用 - After I exit from the remote server(CentOS-7), the `python3 manage.py runserver` will not work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM