Python“FileExists”制作目录时出错 [英] Python "FileExists" error when making directory

查看:2273
本文介绍了Python“FileExists”制作目录时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个集群系统上,我有几个线程从Python并行运行。每个python线程输出到一个目录 mydir 。每个脚本在输出之前检查是否存在,如果不存在,则创建它:

  if if not os。 path.isdir(mydir):
os.makedirs(mydir)

错误:

  os.makedirs(self.log_dir)
文件/usr/lib/python2.6/os .py,第157行,makedirs
mkdir(name,mode)
OSError:[Errno 17]文件存在

我怀疑这可能是由于竞争条件造成的,其中一个工作在另一个创建之前创建了 dir 。这可能吗?如果是这样,这个错误怎么能被避免?



我不确定这是一个竞争条件,所以想知道是否在Python中的其他问题可以导致这个奇怪的错误。

 而True:
mydir = next_dir_name()
try:
os.makedirs(mydir)
break
除了OSError,e:
如果e.errno!= os。 errno.EEXIST:
raise
#time.sleep可能有帮助
pass

如果你有很多线程试图创建一个可预测的系列目录,这仍然会引发很多例外,但是最后你会到达那里。在这种情况下最好只有一个线程创建dirs


I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory mydir. Each script, before outputting checks if mydir exists and if not creates it:

if not os.path.isdir(mydir):
    os.makedirs(mydir)

but this yields the error:

os.makedirs(self.log_dir)                                             
  File "/usr/lib/python2.6/os.py", line 157, in makedirs
mkdir(name,mode)
OSError: [Errno 17] File exists

I suspect it might be due to a race condition, where one job creates the dir before the other gets to it. Is this possible? If so, how can this error be avoided?

I'm not sure it's a race condition so was wondering if other issues in Python can cause this odd error.

解决方案

Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to avoid this (and the usual way in Python) is to just try and then handle the exception

while True:
    mydir = next_dir_name()
    try:
        os.makedirs(mydir)
        break
    except OSError, e:
        if e.errno != os.errno.EEXIST:
            raise   
        # time.sleep might help here
        pass

If you have a lot of threads trying to make a predictable series of directories this will still raise a lot of exceptions, but you will get there in the end. Better to just have one thread creating the dirs in that case

这篇关于Python“FileExists”制作目录时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆