Function for the path of the script?

Roy Smith roy at panix.com
Sun Oct 27 09:38:34 EDT 2013


In article <mailman.1636.1382847023.18130.python-list at python.org>,
 Ben Finney <ben+python at benfinney.id.au> wrote:

> Peter Cacioppi <peter.cacioppi at gmail.com> writes:
> 
> > Am I the only one who finds this function super useful?
> >
> > def _code_file() :
> >     return os.path.abspath(inspect.getsourcefile(_code_file))
> 
> I've used ‘os.path.dirname(os.path.abspath(__file__))’ to find the
> directory containing the current file, in the past. But that was before
> Python's ‘unittest’ module could discover where the test code lives.
> 
> > I've got one in every script. It's the only one I have to copy around.
> > For my workflow ... so handy.
> 
> What workflow requires you to know the filename of the module, within
> the module?

We use:

    config_dir = os.path.abspath(os.path.dirname(__file__))
    songza_dir, _ = os.path.split(config_dir)
    top_dir, _ = os.path.split(songza_dir)
    assert os.path.exists(top_dir + "/.hg")
    return top_dir

in our config files.  This gives us the absolute path to the top of our 
source tree (I don't remember why we do the double os.path.split() 
instead of the more obvious "../..").  We know the file where this code 
lives is two levels down from the top of the source tree.

Once we've got the absolute path to the top of the tree, that's used in 
all sorts of places to locate data files, and to generate configurations 
for other applications (nginx, etc).



More information about the Python-list mailing list