How do I watch a file for changes?

前端 未结 25 2767
孤街浪徒
孤街浪徒 2020-11-21 07:13

I have a log file being written by another process which I want to watch for changes. Each time a change occurs I\'d like to read the new data in to do some processing on it

25条回答
  •  一生所求
    2020-11-21 08:00

    This is an example of checking a file for changes. One that may not be the best way of doing it, but it sure is a short way.

    Handy tool for restarting application when changes have been made to the source. I made this when playing with pygame so I can see effects take place immediately after file save.

    When used in pygame make sure the stuff in the 'while' loop is placed in your game loop aka update or whatever. Otherwise your application will get stuck in an infinite loop and you will not see your game updating.

    file_size_stored = os.stat('neuron.py').st_size
    
      while True:
        try:
          file_size_current = os.stat('neuron.py').st_size
          if file_size_stored != file_size_current:
            restart_program()
        except: 
          pass
    

    In case you wanted the restart code which I found on the web. Here it is. (Not relevant to the question, though it could come in handy)

    def restart_program(): #restart application
        python = sys.executable
        os.execl(python, python, * sys.argv)
    

    Have fun making electrons do what you want them to do.

提交回复
热议问题