How to find script's directory

Papalagi Pakeha papalagi.pakeha at gmail.com
Sun Aug 19 09:19:08 EDT 2007


Hi,

I have a project (a django project actually) that has a structure
something like:
/path/prj/settings.py
/path/prj/scripts/blah.py
/path/prj/...

In order to run blah.py I need to set $PYTHONPATH to /path/prj because
it does "import settings". That's all good. I would however like to
autodetect the path in blah.py somehow and not need to set PYTHONPATH
prior to execution.

Whether it's called as /path/prj/scripts/blah.py or ./blah.py or
../../prj/scripts/blah.py or even plain blah.py should the whole path
to it be in $PATH I'd like it to detect it's location in the
filesystem and append its parent dir to sys.path

I guess I could do it with a little help of os.path.realpath() for all
those cases where absolute or relative path was used. But how should I
approach it when it's invoked as plain 'blah.py' because its directory
name is in $PATH?

TIA!

PaPa



More information about the Python-list mailing list