Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
监视文件是否停止在python中写入_Python_File_Timestamp - Fatal编程技术网

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

监视文件是否停止在python中写入,python,file,timestamp,Python,File,Timestamp,我有一个程序,它每秒钟都会写入一个文件。文件写入是在与UI并行的线程中进行的。由于某些硬件问题,它有时会一天内停止写入。我想检查文件是否停止写入,如果没有更新,请重新启动程序。我想检查文件的时间戳,看看它是否没有更新(也不想访问watchdog等,因为我只需要一个文件停止写入) 这个街区每秒钟都有一次。但这适得其反,当应用程序关闭重新启动时,它每秒钟都会关闭一次,不再启动。我每秒都会记录异常消息。我试着增加时差,但没用 接下来我试着 ftimestamp = os.stat(filename).

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

这个街区每秒钟都有一次。但这适得其反,当应用程序关闭重新启动时,它每秒钟都会关闭一次,不再启动。我每秒都会记录异常消息。我试着增加时差,但没用

接下来我试着

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)

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

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)

要确定GUI程序中的文件是否及时更改,您可以使用事件循环的标准工具,每隔几秒钟运行一个函数,例如,下面介绍如何在
tkinter
中执行此操作:

#!/usr/bin/env python3
import logging
import os
import sys
import tkinter
from datetime import datetime
from time import monotonic as timer, localtime

path = sys.argv[1]
interval = 120 # check every 2 minutes

def check(last=[None]):
    mtime = os.path.getmtime(path) # or os.path.getsize(path)
    logging.debug("mtime %s", datetime.fromtimestamp(mtime))
    if last[0] == mtime: #NOTE: it is always False on the first run
        logging.error("file metadata hasn't been updated, exiting..")
        root.destroy() # exit GUI
    else: # schedule the next run
        last[0] = mtime
        root.after(round(1000 * (interval - timer() % interval)), check)


logging.basicConfig(level=logging.DEBUG,
                    filename=os.path.splitext(__file__)[0] + ".log",
                    format="%(asctime)-15s %(message)s", datefmt="%F %T")
root = tkinter.Tk()
root.withdraw() # hide GUI
root.after(round(1000 * (interval - timer() % interval)), check) # start on boundary
root.mainloop()
您可以使用supervisord、systemd或upstart等自动更新脚本


请参阅。

要确定文件是否在GUI程序中及时更改,您可以使用事件循环的标准工具,每隔几秒钟运行一次函数,例如,下面介绍如何在
tkinter
中执行此操作:

#!/usr/bin/env python3
import logging
import os
import sys
import tkinter
from datetime import datetime
from time import monotonic as timer, localtime

path = sys.argv[1]
interval = 120 # check every 2 minutes

def check(last=[None]):
    mtime = os.path.getmtime(path) # or os.path.getsize(path)
    logging.debug("mtime %s", datetime.fromtimestamp(mtime))
    if last[0] == mtime: #NOTE: it is always False on the first run
        logging.error("file metadata hasn't been updated, exiting..")
        root.destroy() # exit GUI
    else: # schedule the next run
        last[0] = mtime
        root.after(round(1000 * (interval - timer() % interval)), check)


logging.basicConfig(level=logging.DEBUG,
                    filename=os.path.splitext(__file__)[0] + ".log",
                    format="%(asctime)-15s %(message)s", datefmt="%F %T")
root = tkinter.Tk()
root.withdraw() # hide GUI
root.after(round(1000 * (interval - timer() % interval)), check) # start on boundary
root.mainloop()
您可以使用supervisord、systemd或upstart等自动更新脚本


请参阅。

最后,在修改了基于时间戳的选项之后,下面的内容似乎对我有用

try:
    if time.time()-os.stat(filename).st_mtime>6:
        touch(filename)
        raise ValueError("Yikes! Spike")
except ValueError:
    with open('errors.log','a') as log:
        log.write('Spike/App restarting occured at '+ time.strftime(
                "%H:%M:%S")+' on '+datetime.date.today().strftime('%d/%m/%Y')+'\n')
        log.close()
    restart_program()
早些时候,问题是它会检测到文件在给定的时间间隔内停止写入,并继续满足相同的时间间隔

time.time()-os.stat(filename).st_mtime>6 
但一旦满足此条件,除非更新文件时间戳,否则它将继续满足此条件并继续重新启动程序。现在在我的解决方案中,一旦满足条件,我就“接触”了文件(),现在它按预期工作


谢谢大家的意见。

最后,在修改了基于时间戳的选项后,以下内容似乎对我有用

try:
    if time.time()-os.stat(filename).st_mtime>6:
        touch(filename)
        raise ValueError("Yikes! Spike")
except ValueError:
    with open('errors.log','a') as log:
        log.write('Spike/App restarting occured at '+ time.strftime(
                "%H:%M:%S")+' on '+datetime.date.today().strftime('%d/%m/%Y')+'\n')
        log.close()
    restart_program()
早些时候,问题是它会检测到文件在给定的时间间隔内停止写入,并继续满足相同的时间间隔

time.time()-os.stat(filename).st_mtime>6 
但一旦满足此条件,除非更新文件时间戳,否则它将继续满足此条件并继续重新启动程序。现在在我的解决方案中,一旦满足条件,我就“接触”了文件(),现在它按预期工作


感谢大家的投入。

EOFerror!您是否尝试过每秒刷新其输出的写入进程?只检查进程是否仍然存在可能更简单。您可以使用信号0执行
kill(pid,0)
。@therealprashant从技术上讲,文件在写入时始终处于打开状态。我不确定EOFerror是否能帮上忙…@meuh是的!它确实会在每次写入时(每秒)刷新输出,您在谈论哪个进程?是否有单独的文件写入过程?我还在检查文件写入线程是否处于活动状态,BTWEOFerror!您是否尝试过每秒刷新其输出的写入进程?只检查进程是否仍然存在可能更简单。您可以使用信号0执行
kill(pid,0)
。@therealprashant从技术上讲,文件在写入时始终处于打开状态。我不确定EOFerror是否能帮上忙…@meuh是的!它确实会在每次写入时(每秒)刷新输出,您在谈论哪个进程?是否有单独的文件写入过程?我还在检查文件写入线程是否处于活动状态,因为我的UI将严重滞后(使用wx.CallLater函数设置一些文本字段更新!),所以我没有在脚本中使用sleep的特权。最后一个解决方案似乎很有趣。在无限循环脚本中运行无限循环脚本有多安全?该系统的强度有多大?让我测试一下,然后再回到美国。谢谢你的努力。。把无限循环放在无限循环中的方式是非常危险的,但在这种情况下它们是可控的。只要
main.py
运行良好(这就是我们想要的),那么“辅助程序”就处于无限循环中,对于第二个文件,它处于无限循环中,直到文件大小不变,因此它们都是受控的。作为主循环的辅助程序,如果终止,也将终止所有其他程序。第一个解决方案对我不起作用,因为UI挂起,第二个解决方案不起作用,因为文件正在线程中更新,而不是像您假设的那样按顺序更新。尝试其他w