在 python 中监控文件是否停止写入

2024-02-22

我有一个程序每秒不断写入文件。文件写入是在与 UI 并行的线程中进行的。由于某些硬件问题,它有时会停止写入。我想检查文件是否停止写入,如果没有更新则重新启动程序。我想检查文件的时间戳,看看它是否没有更新(并且不想访问看门狗等,因为我只需要文件是否停止写入。)

try:
    if time.time()>(os.stat(filename).st_mtime+2):
        raise ValueError("Yikes! Spike")
except ValueError:
    with open('errors.log','a') as log:
        log.write('Spike occured at '+ time.strftime(
        "%H:%M:%S")+' on '+datetime.date.today().strftime('%d/%m/%Y')+'\n')
        log.close()
    restart_program()

该块每秒运行一次。但这适得其反,当应用程序关闭以重新启动时,它每秒都会关闭并且不会再次启动。我每秒都会收到记录的异常消息。我尝试增加时差,但这没有帮助。

接下来我尝试了

ftimestamp = os.stat(filename).st_mtime
try:
    if os.stat(filename).st_mtime>=ftimestamp:
        ftimestamp = time.time()
        print "ftimestamp updated and all is well"
    else:
        ftimestamp = os.stat(filename).st_mtime
        raise ValueError("Yikes! Spike!")
        print "file time is behind"
except ValueError:
    with open('errors.log','a') as log:
        log.write('Spike occured at '+ time.strftime(
        "%H:%M:%S")+' on '+datetime.date.today().strftime('%d/%m/%Y')+'\n')
        log.close()
    restart_program()

我尝试将变量“ftimestamp”更新为当前时间“time.time()”,因为下一次比较仅在一秒后发生,并且我希望文件时间高于上一次比较的时间。 (该块通过 wx.CallLater 函数每秒运行一次)。

我的程序仍然失败...而且我不明白我哪里出了问题...请有人帮忙!或者有没有一种方法可以简单地检查文件是否停止写入?


我们可以尝试通过执行以下操作来检查文件大小的变化作为可能的解决方案:

import os
from time import sleep
# other imports

while True:
    file1 = os.stat('file.txt') # initial file size
    file1_size = file1.st_size
 
    # your script here that collects and writes data (increase file size)
    sleep(1)
    file2 = os.stat('file.txt') # updated file size
    file2_size = file2.st_size
    comp = file2_size - file1_size # compares sizes
    if comp == 0:
        restart_program()
    else:
        sleep(5)

您可能需要调整sleep()相应地,这些只是我正在使用的估计,因为我无法测试您的实际代码。最后,这是一个无限循环,只要您希望脚本继续写入,它就会继续运行。

另一种解决方案是将您的代码更新为:

import os
import sys
from time import sleep
# other imports

while True:
    file1 = os.stat('file.txt') # initial file size
    file1_size = file1.st_size
 
    # your script here that collects and writes data (increase file size)
    sleep(1)
    file2 = os.stat('file.txt') # updated file size
    file2_size = file2.st_size
    comp = file2_size - file1_size # compares sizes
    if comp == 0:
        sys.exit
    else:
        sleep(5)

然后使用辅助程序来运行脚本,如下所示:

import os
from time import sleep, strftime

while True:
    print(strftime("%H:%M:%S"), "Starting"))
    system('main.py') # this is another infinite loop that will keep your script running
    print(strftime("%H:%M:%S"), "Crashed"))
    sleep(5)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 python 中监控文件是否停止写入 的相关文章

随机推荐