B. Shefter
B. Shefter

Reputation: 897

How to handle os.stat() permission issue? (Python 2.7)

I'm trying to create a subdirectory if it doesn't already exist. Here is the relevant portion of my function (TMP is the constant "-InProg"):

def create_directories(parent, tmp_dir=""):
    """
    Terminates program if tmp_dir already exists; otherwise
    creates subdirectories that don't already exist
    """
    if not tmp_dir:
        tmp_dir = parent + TMP
    try:
        if os.path.exists(tmp_dir):
            LOGGER.error('Automation already running')
            return False
        else:
            os.makedirs(tmp_dir)
        <...snip...>
    except OSError:
        LOGGER.error('Directory %s not valid', parent, exc_info=True)
        sys.exit("ERROR: Directory " + parent + " not valid")

Here is the relevant portion of the log:

ERROR:Directory <parent> not valid
Traceback (most recent call last):
  File "</path/to/my/script>.py", line 139, in create_directories
    os.makedirs(tmp_dir)
  File "/usr/local/Cellar/python@2/2.7.17/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 17] File exists: '<parent>-InProg'

Clearly tmp_dir already exists. But if tmp_dir exists then the code shouldn't reach os.makedirs(tmp_dir) at all, right? Yet that is definitely the specific line throwing the OSError.

The only clue I've been able to find is that the documentation for os.path.exists() says, "On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists." If this is the problem, what can I do about it?

NOTE: This explanation seems a bit unlikely, because the program itself is what creates tmp_dir, and I can't imagine it being able to create a subdirectory that it doesn't have permission to stat(). I can't think of an alternate explanation, though. Am I missing some other incredibly obvious bug?

Upvotes: 1

Views: 892

Answers (0)

Related Questions