为什么这个看门狗脚本不能在我的主文件夹中工作?

时间:2014-08-07 15:08:51

标签: python python-3.x python-watchdog

我正在编写一个python脚本,用于观察某个文件夹中的更改:

#!/usr/bin/env python3

import time
import os
import subprocess

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

class MyHandler(PatternMatchingEventHandler):
    patterns = ["*.txt", "*.html"]
    # targetDir = "/Users/kaiyin/Movies/screencasts_small/"

    def process(self, event):
        # p = subprocess.Popen(["/usr/local/bin/CocoaDialog", "bubble", "--title", "Watch folder", "--text", "New file" + event.src_path],
        #                  stdout=subprocess.PIPE,
        #                  stderr=subprocess.PIPE)
        # out, err = p.communicate()
        print("Something happened...")

    def on_created(self, event):
        print("Triggered...")
        self.process(event)
    def on_modified(self, event):
        print("Triggered...")
        self.process(event)

if __name__ == "__main__":
    arg = "/Users/kaiyin/Movies/screencasts"
    os.system("ls " + arg)
    observer = Observer()
    observer.schedule(MyHandler(), path=arg if arg else ".")
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


# import os
# mystat = os.stat("/Users/kaiyin/Movies/screencasts")
# mystat[0]
# oct(mystat[0])
# int(oct(mystat[0]), 8)

问题是文件的创建和修改根本不会触发流程功能,但如果我更改arg = "/tmp/somefolder",那么它完全有效。我现在很困惑。

文件夹的许可:

drwxr-xr-x  7 kaiyin  staff   238B Aug  7 17:03 /Users/kaiyin/Movies/screencasts/

1 个答案:

答案 0 :(得分:0)

我不知道这个watchdog模块,但你用ohter方法检查目录

while True:
    now = datetime.datetime.now()
    ago = now - datetime.timedelta(seconds=60)

    file_list = []
    for path in glob.glob(FILES + "/*.avi"):
        (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(path)

        if datetime.datetime.fromtimestamp(mtime) > ago:
            file_list.append(path)

    if(file_list): 
        ## process yuor list
        process(file_list)

    time.sleep(30)

此代码检查文件的修改时间并将其放入file_list。您可以扩展此验证并将信息放在dictionary中以检测文件中的更改。