Forums

Module watchdog is not being triggered

I have created one script that is using watchdog module. I can't see no errors in log, but I copy files to monitored folder and the event is not triggered. I have tried with both python 2.7 and 3.4. The last message I can see in the logs is: Starting Process, which indicates that all config file load and log object are ok and it should enter on the While True loop and wait for files....

Can someone help me? the code is below.

# ---------------------------------------------------------------------------------------------------------------------
class DataHandler(PatternMatchingEventHandler):
patterns = ['*.csv', '*.txt']

def on_any_event(self, event):
    global file_config
    global log_obj

    log_obj.info(event.event_type)
    print(event.event_type)
    if event.event_type in ['created'] and not event.is_directory:
        print('Waiting the copy operation for file %s to finish.' % event.src_path)
        log_obj.info('Waiting the copy operation for file %s to finish.' % event.src_path)
        size1 = -1
        while True:
            size2 = os.path.getsize(event.src_path)
            if size1 == size2:
                break
            size1 = size2
            time.sleep(2)

        log_obj.info('Processing file %s.' % event.src_path)

        row_cnt = load_from_csv(event.src_path, file_config, log_obj)

        if not os.path.exists(file_config.archive_folder):
            os.makedirs(file_config.archive_folder, mode=0o777)

        shutil.move(event.src_path, os.path.join(file_config.archive_folder, os.path.basename(event.src_path)))

        log_obj.info('File %s imported. Rows imported: %s' % (event.src_path, str(row_cnt)))


# ---------------------------------------------------------------------------------------------------------------------
def execute(cfg_name='/home/absolutereg/task/file_watcher.config'):
global file_config
global log_obj

return_value = 0

print(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
print("Loading Configuration...")

file_config = labio.configWrapper.load_configuration(cfg_name)

if file_config.isLoaded:
    # Initializing the log system
    log_obj = None
    try:
        log_obj = labio.logWrapper.return_logging(file_config.log)
    except:
        return_value = 1
        print(traceback.format_exc())

    if return_value == 0:
        try:
            log_obj.info('Starting process...')

            event_handler = DataHandler()

            observer = Observer()
            observer.schedule(event_handler, path=file_config.watch_folder, recursive=False)
            observer.start()

            try:
                while True:
                    time.sleep(1)
            except:
                log_obj.error(traceback.format_exc())
                observer.stop()

            observer.join()

            log_obj.info('Ending process...')
        except:
            return_value = 1
            log_obj.error('Unexpected error: %s' % traceback.format_exc())
            log_obj.info('Execution aborted due to errors. Please see the log file for more details.')
    else:
        return_value = 1
else:
    print('Config file not loaded. %s' % cfg_name)
    return_value = 1

return return_value

I've discovered that the problem is somehow related to permission. The problem was happening with me, as a teacher, trying to run the script. When my student executed by himself, the script have worked fine. I still need a more professional answer.

False alarm, for some reason, it is not working again. The same code, but does not work anymore.

PythonAnywhere uses a networked file system (specifically, NFS) so that your file are visible from the different servers that run it -- a mixture of web servers, console servers, and scheduled task servers. So unfortunately anything that depends on watching the filesystem using the normal inotify-based system calls won't work reliably, especially if you modify a file on one server and are monitoring it on another. The times when it did appear to work may have been cases where your code happened to be running on the same console server as the code that modified the files, though I don't think it will be 100% reliable even in that case.

Thanks, Giles. I was reading about that ... I'll change the strategy of my code.

If you are already a user of tmux/screen that could be an easy way to make sure that you are watching on the same server as the file change.