0

I've got a small script with monitors when files are added or removed to a directory. The next step is for me to get the script to execute the files (windows batch files) once they’ve been added to the directory. I’m struggling to understand how to use a variable with subprocess call (if this is the best way this can be acheived). Could anyone help me please? Many thanks. Code looks like this so far ;

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)
user2377057
  • 183
  • 1
  • 1
  • 11

1 Answers1

1

This should do what you wanted, cleaned it up a little.

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
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131