带有文件名变量的 Python 子进程调用 [英] Python Sub process call with filename variable

查看:39
本文介绍了带有文件名变量的 Python 子进程调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

这应该可以满足您的需求,稍微清理一下.

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

这篇关于带有文件名变量的 Python 子进程调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆