【发布时间】:2015-09-30 06:19:27
【问题描述】:
我有一个程序每秒都在写入文件。文件写入发生在与 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 函数每秒运行一次)。
我的程序仍然失败......而且我无法理解我哪里出错了......请有人帮忙!或者有没有办法简单地检查文件是否停止写入?
【问题讨论】:
-
EOF错误!你试过了吗
-
写入过程是否每秒刷新一次输出?
-
只检查进程是否仍然存在可能更简单。为此,您可以使用信号 0 执行
kill(pid,0)。 -
@therealprashant 从技术上讲,文件在写入时始终处于打开状态。我不确定 EOFerror 是否可以在这里提供帮助...
-
@meuh 是的!每次写入时(每秒)它都会刷新输出,您在说哪个进程?是否有单独的文件写入过程?我也在检查文件写入线程是否还活着 BTW