Search code examples
pythonserial-portarduinogame-maker

How to watch a file for modifications OS X and Python


I'm working on a small game with a physical interface that requires me to write a character to the serial port with python every time a particular file in a directory is modified. The file in question is going to be modified probably every 20 - 30 seconds or so while the game is being played.

What is the best method to do this with?

I've been reading a few threads about this including:

How do I watch a file for changes?

How to get file creation & modification date/times in Python?

...but I'm not sure which method to go with. Suggestions?

Edit: Ok, I'd like to use a basic polling method for this. It doesn't have to scale, so small, with no having to upgrade or instal stuff = fine. If anyone has some links or resources on how to use os.path.getmtime() to do this, that would be helpful

ie: How do I go about writing an event loop using this that will notice when the modified date has been changed?

Basically:

  1. Look the time stamp of a file
  2. store that time stamp in a variable called [last_mod]
  3. look at that time stamp again in 5 seconds
  4. if the current time stamp is different than the saved timestamp execute a function and then replace the value of [last_mod] with the current_time stamp

repeat...

Thank You

PS. sorry for the edits.


Solution

  • A simple polling loop would look something like this:

    import time
    import os
    
    mtime_last = 0
    while True:
        time.sleep(5)
        mtime_cur = os.path.getmtime("/path/to/your/file")
        if mtime_cur != mtime_last:
            do_stuff()
        mtime_last = mtime_cur