Skip to main content
 首页 » 编程设计

python之使 python 脚本在 x 秒不活动后退出

2024年10月25日13JeffreyZhao

我有一个用于我的树莓派的脚本,它可以持续读取数据并将数据保存到文件中。但是我知道这很危险,因为如果在保存数据时断电,SD 卡确实存在损坏的风险。

如果计算机在一段时间内处于非事件状态,有没有办法让脚本自行终止?

抱歉,如果这个问题含糊不清,但我什至不知道从哪里开始,所以我无法展示我尝试过的任何代码。

请您参考如下方法:

这是一个天真的看门狗实现:

import os 
import signal 
import threading 
 
 
 
class Watchdog(): 
    def __init__(self, timeout=10): 
        self.timeout = timeout 
        self._t = None 
 
    def do_expire(self): 
        os.kill(os.getpid(),signal.SIGKILL) 
 
    def _expire(self): 
        print("\nWatchdog expire") 
        self.do_expire() 
 
    def start(self): 
        if self._t is None: 
            self._t = threading.Timer(self.timeout, self._expire) 
            self._t.start() 
 
    def stop(self): 
        if self._t is not None: 
            self._t.cancel() 
            self._t = None 
 
    def refresh(self): 
        if self._t is not None: 
             self.stop() 
             self.start() 

通过 wd = Watchdog() 构建它每次你得到一些可以满足你工作需要的东西时,都会调用wd.refresh() .如果您在超时结束前不调用刷新,它将调用 os.kill(os.getpid(),signal.SIGKILL) .

你不能只使用 sys.exit()因为它只引发 SystemExit异常(exception):使用 kill随心所欲。

现在您可以使用一些东西来轮询系统并使用答案来刷新或不刷新看门狗。例如xprintidle告诉你 X 空闲时间,但这一切都取决于你需要监控的内容。

使用示例

timeout=10 
wd = Watchdog(timeout) 
wd.start() 
while True: 
    a=str(raw_input('Tell me something or I will die in {} seconds: '.format(timeout))) 
    wd.refresh() 
    print("You wrote '{}'... you win an other cycle".format(a[:-1))