local variable referenced before assignment

johngilbrough johngilbrough at gmail.com
Mon Apr 5 00:12:10 CEST 2010


I cannot make sense of what's happening here ...  I'm getting the
following error:

initializing last modified time
/home/john/Dropbox/Projects/python/scripts/src 29
referencing last modified time
/home/john/Dropbox/Projects/python/scripts/src 29
referencing last modified time
Traceback (most recent call last):
  File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py",
line 42, in <module>
    time.sleep(10000)
  File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py",
line 18, in handler
    if modifiedTime <> lastModifiedTime:
UnboundLocalError: local variable 'lastModifiedTime' referenced before
assignment

>From this logic:

#!/usr/bin/python
def watchFile(filePath, callback):
    ###
    #   calls callback whenever file is changed
    ###
    import fcntl
    import os
    import signal
    print "initializing last modified time"
    lastModifiedTime = os.path.getmtime(filePath)

    def handler(signum, frame):
        ## this gets called twice whenever a file changes
        print filePath + " " + str(signum)
        modifiedTime = os.path.getmtime(filePath)
        print "referencing last modified time"
        if modifiedTime <> lastModifiedTime:
            lastModifiedTime = modifiedTime
            callback()

    signal.signal(signal.SIGIO, handler)
    fd = os.open(filePath,  os.O_RDONLY)
    fcntl.fcntl(fd, fcntl.F_SETSIG, 0)
    fcntl.fcntl(fd, fcntl.F_NOTIFY,
        0
        | fcntl.DN_MODIFY
        | fcntl.DN_CREATE
        | fcntl.DN_MULTISHOT  # what's this?
        )

def doSomething ():
    print "in doSomething"

import time
filePath = "/home/john/Dropbox/Projects/python/scripts/src"

watchFile (filePath, doSomething)

while True:
    # needed to keep this alive - gets interrupted when a file changes
    time.sleep(10000)
    print "*",



More information about the Python-list mailing list