使用filename变量进行Python Subprocess调用

时间:2013-07-10 12:55:56

标签: python subprocess

我在文件添加或删除到目录时有一个带监视器的小脚本。下一步是让我在脚本添加到目录后让脚本执行文件(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)

1 个答案:

答案 0 :(得分: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