0

当文件被添加或删除到目录时,我有一个带有监视器的小脚本。下一步是让我在将文件(Windows 批处理文件)添加到目录后执行脚本。我正在努力理解如何在子进程调用中使用变量(如果这是实现这一目标的最佳方式)。有人可以帮我吗?非常感谢。到目前为止,代码看起来像这样;

import sys
import time
import os

inputdir = 'c:\\test\\'
os.chdir(inputdir)
contents = os.listdir(inputdir)
count = len(inputdir)
dirmtime = os.stat(inputdir).st_mtime

while True:
newmtime = os.stat(inputdir).st_mtime
if newmtime != dirmtime:
    dirmtime = newmtime
    newcontents = os.listdir(inputdir)
    added = set(newcontents).difference(contents)
    if added:
        print "These files added: %s" %(" ".join(added))
        import subprocess
        subprocess.call(%,shell=True)

    removed = set(contents).difference(newcontents)
    if removed:
        print "These files removed: %s" %(" ".join(removed))

    contents = newcontents
time.sleep(15)
4

1 回答 1

1

这应该做你想要的,清理一下。

import sys
import time
import os
import subprocess

def monitor_execute(directory):
    dir_contents = os.listdir(directory)
    last_modified = os.stat(directory).st_mtime
    while True:
        time.sleep(15)
        modified = os.stat(directory).st_mtime
        if last_modified == modified:
            continue
        last_modified = modified
        current_contents = os.listdir(directory)
        new_files = set(current_contents).difference(dir_contents)
        if new_files:
            print 'Found new files: %s' % ' '.join(new_files)

        for new_file in new_files:
            subprocess.call(new_file, shell=True)

        lost_files = set(dir_contents).difference(current_contents)
        if lost_files:
            print 'Lost these files: %s' % ' '.join(lost_files)

        dir_contents = current_contents
于 2013-07-10T13:04:33.843 回答