Monitoring if a file stopped writing in python

前端 未结 3 1566
一个人的身影
一个人的身影 2021-01-16 19:48

I have a program that keeps writing to a file every second. File writing is happening in a thread parallel to the UI. Due to some hardware issue it stops writing sometimes o

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-16 20:39

    Finally, after tinkering around with timestamp based options, the following seemed to work for me.

    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()
    

    Earlier, the problem was it would detect that the file stopped writing with the given time interval and continue to satisfy the same.

    time.time()-os.stat(filename).st_mtime>6 
    

    But once this condition is satisfied, unless the file timestamp is updated it continues to satisfy this condition and would keep restarting the program. Now in my solution, I 'touched' the file once (touch used from here) the condition is satisfied and now it works as expected.

    Thank you all for your inputs.

提交回复
热议问题