带有filename变量的Python子进程调用
我有一个小脚本,当文件被添加或删除到一个目录时,它带有监视器。下一步是让脚本在文件(windows批处理文件)添加到目录后执行这些文件。我正在努力理解如何在子流程调用中使用变量(如果这是实现此目的的最佳方式)。谁能帮我一下吗?非常感谢。到目前为止,代码看起来是这样的带有filename变量的Python子进程调用,python,subprocess,Python,Subprocess,我有一个小脚本,当文件被添加或删除到一个目录时,它带有监视器。下一步是让脚本在文件(windows批处理文件)添加到目录后执行这些文件。我正在努力理解如何在子流程调用中使用变量(如果这是实现此目的的最佳方式)。谁能帮我一下吗?非常感谢。到目前为止,代码看起来是这样的 import sys import time import os inputdir = 'c:\\test\\' os.chdir(inputdir) contents = os.listdir(inputdir) count =
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)
这应该是你想要的,清理一下
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