0

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"])  
ndmeiri
  • 4,979
  • 12
  • 37
  • 45
SamAtWork
  • 455
  • 5
  • 17

1 Answers1

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]
crookedleaf
  • 2,118
  • 4
  • 16
  • 38
  • Ah! I am assuming (https://stackoverflow.com/questions/43274476/is-there-a-way-to-check-if-a-subprocess-is-still-running) would be the way to go about checking if process is still running! – SamAtWork Jun 14 '18 at 20:02
  • @TheOne yes. i just update my answer to show a way to wait until the subprocess is done before removing your directory. – crookedleaf Jun 14 '18 at 20:14