What is a good solution for fake OSError, 13 (EACCES) using Python on Windows

Here is the code:

def make_dir(dir_name): if os.path.exists(dir_name): shutil.rmtree(dir_name) try: os.makedirs(dir_name) except OSError, e: print "ErrorNo: %s (%s)" % (e.errno, errno.errorcode[e.errno]) raise 

IFF, the directory already exists, I get the following:

 ErrorNo: 13 (EACCES) Traceback (most recent call last): File "run_pnoise.py", line 167, in <module> make_dir("prep_dat") File "run_pnoise.py", line 88, in make_dir os.makedirs(dir_name) File "c:\Program Files (x86)\Python27\lib\os.py", line 157, in makedirs mkdir(name, mode) WindowsError: [Error 5] Access is denied: 'prep_dat' 

If I run the program again, it works, indicating that the program really has access to directories, since the shutil.rmtree call works fine. I came up with a workaround that I will post. However, is there a better explanation and / or workaround?

My guess is that the shutil.rmtree call is returned before the OS completes the deletion of all files and subdirectories completely. Also, since the shutil.rmtree call does not throw an exception, any EACCESS (13) error in the makedirs call is probably fictitious. My attempt (modified after Apalala's comment):

 def make_dir(dir_name): retry = True if os.path.exists(dir_name): shutil.rmtree(dir_name) while retry: try: # per Apalala, sleeping before the makedirs() eliminates the exception! time.sleep(0.001) os.makedirs(dir_name) except OSError, e: #time.sleep(0.001) # moved to before the makedirs() call #print "ErrorNo: %s (%s)" % (e.errno, errno.errorcode[e.errno]) if e.errno != 13: # eaccess raise else: retry = False 

This seems to work reliably. Other posts have a race condition problem, however this seems unlikely and is likely to result in another exception.

+4
source share
3 answers

I had the same problem and this seems to be my solution, except that I was sleeping (0.1).

0
source

Can't you just use the "except" statement?

 def make_dir(dir_name): retry = True if os.path.exists(dir_name): shutil.rmtree(dir_name) while retry: try: os.makedirs(dir_name) except OSError, e: time.sleep(0.001) if e.errno != 13: # eaccess raise except WindowsError: # (do some stuff) else: retry = False 

It should work, no ?!

0
source

In a previous post, you said that the program raised a "WindowsError" exception:

 WindowsError: [Error 5] Access is denied: 'prep_dat' 

Your code can handle OSError exceptions with the except statement, but it cannot handle WindowsError exceptions ... if you want to handle WindowsError exceptions, you should use the except statement like this:

  except WindowsError: # (do some stuff) 

Please note that you can handle any exceptions, such as:

 except Exception, e: # this code will catch all raised exceptions. The variable ยซeยป contains an instance of the raised exception. 
0
source

Source: https://habr.com/ru/post/1334431/


All Articles