How to find script's directory

P

Papalagi Pakeha

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
 
J

Jeffrey Froman

Papalagi said:
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?


Use the value of __file__ rather than sys.argv[0] -- it contains the
directory information. You may still need to normalize the value using
various os.path functions.


Jeffrey
 
T

Tuomas

#!/usr/bin/python
# module show_my_path
# ...
import os
print 'os.path.abspath(__file__):', os.path.abspath(__file__)
# ...
# end of module

[tv@tux class]$ python[tv@tux class]$ python show_my_path.py
os.path.abspath(__file__): /misc/proc/py/test/class/show_my_path.py
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,235
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top