开发者

Python Watch Folder - interrogating list for filesize

I'm trying to get the following code to watch a folder for changes and return the filename (preferably a full path) as a string once it's checked that the filesize hasn't increased recently, to stop the rest of my script inspecting incomplete files. I'm having difficulty with sending my filesize timer function a filename because i'm collecting the detected files as a list. If i'm barking up the wrong tree feel free to tell me, and thanks for any help!

Stewart

import os, time

def watch(path_to_watch):
    before = dict ([(f, None) for f in os.listdir (path_to_watch)])
    while watch_active == 1:
        time.sleep (10)
        after = dict ([(f, None) for f in os.listdir (path_to_watch)])
        added = [f for f in after if not f in before]
        removed = [f for f in before if not f in after]
        if added:
            filesizechecker(added)
            return added
        if removed:
            print "Removed: ", ", ".join (removed)
      开发者_如何学编程  before = after

def filesizechecker(filepath):
# Checks filesize of input file and 
# returns 1 when file hasn't changed for 3 seconds
    fnow = open(filepath, "rb")
    fthen = 1
    while fnow != fthen:
        time.sleep(3)
        fthen = len(f.read())

watch_active = 1
watch("/home/stewart/Documents")


You could also check how lsof works. It lists the open files. If the file you're watching (or want) isn't open it is also not probable that it is being changed.

You're on Linux so you can always check the /proc filesystem for information on processes and files.

I don't know the details, so it's upt o you weather this line of thinking is worth your time:)


I did some more research and discovered the pyinotify library was much more suited to my needs.

Specifically the IN_CLOSE_WRITE Event Code returns when an application (in my case, a file copy) closes a writable file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜