0

I have a tkinter GUI that at some point prompts the user for a folder, checks if it exists, and then, if it does and the user consents, deletes and recreates it. I am doing this via the following code:

try:
   self.status_string.set('Cleaning up output directory to be overwritten')
   shutil.rmtree(output_folder)
   while os.path.exists(output_folder):
       time.sleep(1)
    os.makedirs(output_folder + '/events')
except OSError:
    self.status_string.set('Failed to create directory {0}, verify that you have permission to do so'.format(output_folder + '/events'))

I am currently calling time.sleep in order to force it to wait until the directory has been completely removed before trying to recreate it, because the contents can be large and it may take a while and I want to avoid the race condition. But it seems wrong to me to be using sleep during the mainloop of tkinter, and I am not certain that checking for existence after calling rmtree is valid. It seems to work in testing, but that could be luck. What is the proper way to wait for the system call to resolve before proceeding?

KBriggs
  • 1,220
  • 2
  • 18
  • 43
  • 1
    ***wait until the directory has been completely removed***: Why do you think the function returns before it completes? This is a long running task which will block the`tkinter` mainloop. – stovfl Apr 17 '20 at 16:28
  • perhaps I misunderstood the answer in another question, then. https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty/43914402#43914402 suggests there are potential race conditions, which I assumed was due to the system call not blocking. Is that inaccurate? – KBriggs Apr 17 '20 at 16:44
  • 1
    ***there are potential race conditions***: The function can raise **OSError**, e.g. due to permissions. – stovfl Apr 17 '20 at 16:59
  • Ah, so it needs its own try/ except block – KBriggs Apr 17 '20 at 17:44

0 Answers0