Easier way to get the "here" path?

MRAB google at mrabarnett.plus.com
Sat Jul 26 12:26:23 EDT 2008


On Jul 25, 10:08 pm, bukzor <workithar... at gmail.com> wrote:
> 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'

How about:

import os
import sys
here = os.path.realpath(os.path.dirname(sys.argv[0]))

It's a little clearer. :-)



More information about the Python-list mailing list