代码如下:
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 目录已经存在,我得到以下信息:
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'
如果我再次运行该程序,它会工作,表明该程序确实可以访问目录,因为 shutil.rmtree 调用显然在工作。我想出了一个解决方法,我将发布它。但是,是否有更好的解释和/或解决方法?
我的假设是 shutil.rmtree 调用在操作系统完全删除所有文件和子目录之前返回。此外,由于 shutil.rmtree 调用没有抛出异常,因此 makedirs 调用上的任何 EACCESS (13) 错误都可能是假的。我的尝试(根据 Apalala 的评论修改):
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
这似乎工作可靠。其他帖子中提到了竞争条件问题,但这似乎不太可能,并且可能会导致不同的异常。
最佳答案
我遇到了同样的问题,这看起来与我的解决方案相似,只是我在 sleep (0.1)。
关于python - 在 Windows 上使用 Python 解决伪造的 OSError, 13 (EACCES) 的好方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4609572/