问题
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