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

笑着哭i 提交于 2019-12-11 21:52:08

问题


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"])  

回答1:


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]


来源:https://stackoverflow.com/questions/50864930/how-to-delete-files-directories-after-subprocess-is-done-with-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!