python - 在 Windows 上使用 Python 解决伪造的 OSError, 13 (EACCES) 的好方法是什么

标签 python windows exception directory shutil

代码如下:

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/

相关文章:

python - 如何在Python中快速检查和统计英语语法错误?

Python - 将列表转换为列表列表,每个条目包含唯一组合

windows - 渲染透明窗口

windows - cmake 在调用 'git' 命令时无法读取 ssh key

windows - CreateFile API 的性能下降

node.js - 在 Promise 中引发时未显示异常

c# - 我可以拥有强大的异常安全和事件吗?

python - 拆分一个巨大的 WSDL 文件

python - Lookahead 正则表达式无法找到相同的重叠匹配项

java - Java 1.6.0 中的 UnsupportedClassVersionError 异常