Wednesday, November 14, 2012

python working directory


import inspect
import sys
import os.path


def caller_directory():
    mod_name = inspect.currentframe().f_back.f_back.f_globals.get('__name__')
    module = sys.modules[mod_name]
    if not hasattr(module, '__file__'): #probably REPL
        return os.getcwd()
    path = module.__file__
    #now, where does this path meet the python path?
    if os.path.isabs(path): #already absolute path? hurray, we are done
        return os.path.dirname(path)
    #otherwise, need to go down the python path finding where it joins
    for p in sys.path:
        p = os.path.join(p, path)
        if os.path.exists(p):
            return os.path.dirname(os.path.abspath(p))
    raise Exception("could not find caller directory")
    
This function, when called, will return the directory of the current functions caller.

This allows for directory normalization.  A call to open() will always be relative to the current working directory.  This way, the directory relative to the __file__ of the caller can be found.  In some cases, this is what a user would intuitively expect.

No comments:

Post a Comment