子进程完成后如何删除文件/目录?

How to delete Files / Directories after Subprocess is done with them?

我正在使用 Watchdog 来监控一个目录。如果添加任何新目录,我想在那些 "Source" 目录上启动子进程,并在将输出一些文件的目录上调用程序 anon_local

我的问题是:在我的子进程完成该目录后删除目录及其内容的优雅方式是什么?

class Handler(FileSystemEventHandler):
    @staticmethod
    def on_any_event(event):
        if event.is_directory and event.event_type == 'created':
            PATH = event.src_path
            proc = subprocess.Popen(["python2", "anon_local.py" , PATH, "-t", "target directory", "-csv", "arg", "-p", "arg"])  

这可以通过 shutil's rmtree 函数来完成。

只要PATH是你要删除的目录,只要检查确保你的子进程已经完成,然后运行 shutil.rmtree(PATH)

如果您需要等到子流程完成,您可以通过在 proc 上调用 .poll() 并等待它 return None 来完成此操作。例如:

while proc.poll() == None:  # .poll() will return a value once it's complete. 
    time.sleep(1)
[then remove your directory here]