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.

1 comment:

  1. It's fascinating to read this Python blog. By the way, I appreciate you sharing your webpage because I came into it when browsing the coursework writing help. Python is a programming language that may be used to build apps and websites, automate procedures, and perform data analysis.