监视附加文件并在追加完成后执行一些操作

时间:2014-04-20 07:04:28

标签: python watchdog file-monitoring

我已经创建了2个单独的脚本来抓取,抓取并将结果保存到csv文件,并将文件上传到我手动运行的dropbox。现在我想要的是在执行追加操作时监视csv文件,然后在追加操作结束后上传文件。任何人都可以向我提出一些想法或例子,因为我是新手。我看到一个名为看门狗的软件包,但无法弄清楚如何使用它。

2 个答案:

答案 0 :(得分:3)

watchdog非常简单易用。我在这里编写了示例代码,它将监视*.csv文件的更改。在使用之前设置路径...简单的./也可以:

import time

from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

class ChangeHandler(PatternMatchingEventHandler):
    patterns = ["*.csv"] # Only handle csv files

    def __init__(self):
        super(ChangeHandler, self).__init__()

    def process(self, event):
        '''
        event.event_type: The type of the event as a string.
        event.src_path: Source path of the file system object
                that triggered this event
        event.is_directory: True if event was emitted for
                a directory; False otherwise.
        '''
        print event.event_type
        print event.src_path
        print event.is_directory
        # DO UPLOAD HERE

    def on_modified(self, event):
        self.process(event)

    def on_created(self, event):
        self.process(event)

    def on_deleted(self, event):
        '''
        file is deleted, maybe do some other operations?
        '''
        pass

if __name__ == '__main__':
    observer = Observer()
    observer.schedule(ChangeHandler(), path='your_csv_folder_path_here',
                      recursive=True)
    observer.start()
    while True:
        time.sleep(1)

答案 1 :(得分:0)

您可以探索Pynotify。虽然我没有亲自使用它。