子进程完成后如何删除文件

子进程完成后如何删除文件

本文介绍了子进程完成后如何删除文件/目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

class Handler(FileSystemEventHandler):@静态方法def on_any_event(event):如果 event.is_directory 和 event.event_type == 'created':PATH = event.src_pathproc = subprocess.Popen(["python2", "anon_local.py", PATH, "-t", "目标目录", "-csv", "arg", "-p", "arg"])
解决方案

这可以通过 shutilrmtree 函数.

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

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

while proc.poll() == None: # .poll() 将在完成后返回一个值.时间.睡眠(1)[然后在此处删除您的目录]

I am using Watchdog to monitor a directory. If any new directories are added, I want to start subprocesses on those "Source" directories and call a program anon_local on the directories which will output some files.

My question is: What would be an elegant way of deleting the directories and their content after my subprocesses are done with that directory?

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"])
解决方案

This can be done with shutil's rmtree function.

So long as PATH is the directory you want deleted, just check to make sure your subprocess has finished, and then just run shutil.rmtree(PATH)

If you need to wait until your subprocess is done, you can accomplish this by calling .poll() on your proc and waiting for it to return None. For example:

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

这篇关于子进程完成后如何删除文件/目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:38