[issue1675] Race condition in os.makedirs

Zooko O'Whielacronx report at bugs.python.org
Tue Nov 11 23:59:36 CET 2008


Zooko O'Whielacronx <zooko at zooko.com> added the comment:

Here's the version of this that I've been using for almost a decade now:

http://allmydata.org/trac/pyutil/browser/pyutil/pyutil/fileutil.py?rev=127#L241

Actually I used to have a bigger version that could optionally require
certain things of the mode of the directory, but it turned out that I
wasn't going to need it.

def make_dirs(dirname, mode=0777):
    """
    An idempotent version of os.makedirs().  If the dir already exists, do
    nothing and return without raising an exception.  If this call
creates the
    dir, return without raising an exception.  If there is an error that
    prevents creation or if the directory gets deleted after make_dirs()
creates
    it and before make_dirs() checks that it exists, raise an exception.
    """
    tx = None
    try:
        os.makedirs(dirname, mode)
    except OSError, x:
        tx = x

    if not os.path.isdir(dirname):
        if tx:
            raise tx
        raise exceptions.IOError, "unknown error prevented creation of
directory, or deleted the directory immediately after creation: %s" %
dirname # careful not to construct an IOError with a 2-tuple, as that
has a special meaning...

----------
nosy: +zooko

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue1675>
_______________________________________


More information about the Python-bugs-list mailing list