Easier way to get the "here" path?

bukzor workitharder at gmail.com
Fri Jul 25 17:08:01 EDT 2008


I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:

from os.path import dirname, realpath, abspath
here = dirname(realpath(abspath(__file__.rstrip("c"))))

In particular, this takes care of the case of symlinked, compiled
scripts, which is fairly common at my workplace, and I imagine in many
*nix evironments.


An illustration:
$echo "print __file__" > symlinks/path.py
$ln -s symlinks/path.py
$python
>>> import path
path.py
>>> reload(path)
path.pyc
<module 'path' from 'path.pyc'>
>>> path.__file__
'path.pyc'
>>> path.__file__.rstrip("c")
'path.py'
>>> from os.path import abspath, realpath
>>> realpath(path.__file__.rstrip("c"))
'/home/bgolemon/python/symlinks/path.py'
>>> realpath(abspath(path.__file__.rstrip("c")))
'/home/bgolemon/python/symlinks/symlinks/path.py'



More information about the Python-list mailing list