Customizing the python search path depending on source directory

Peter Schwalm peter.schwalm at epost.de
Tue Apr 6 22:53:51 EDT 2004


I'd like to modify the python search path depending on the source
directory of the script being started. The reason is: I use a version
control system, and the python scripts and modules are migrated
through several stages before they are used in production. A python
script running in a development environment should use different
modules - possibly in other directories then the script source
directory - than the same script running in a production environment.

Ideally this should work without any modifications to the python
programs, and the search path should be set up before the script
invoked by the user gains control.

My idea was to use site.py / sitecustomize.py in lib/site-packages and
to have sitecustomize.py invoke a directory-specific customizing
module - say dirCustomize.py - located in the script source directory.

But it seems that this is the wrong place, because at the moment
sitecustomize is imported

    a) the source directory of the script is still not in sys.path
    b) sys.argv is still not set, so I can't find out the source
directory via sys.argv[0] and temporarily add it to sys.path for the
invocation of dirCustomize.py.
    c) also sys.modules["__main__"].__file__ is still not set

The following "sitecustomize.py" shows these difficulties:
#-------------------------------------------------------------------------
print "start siteCustomize.py ..."
import sys
import os

try:
    print "argv=", sys.argv
except AttributeError:
    print ""
    print "sys.argv does still not exist!"

try:
    print "sys.modules[\"__main__\"]=",
sys.modules["__main__"].__file__
except AttributeError:
    print ""
    print "sys.modules[\"__main__\"].__file__ does still not exist"

# ... shows that source directory is still not in sys.path
print "sys.path="
for ix1, p1 in enumerate(sys.path):    print "%02.02d: %s" % (ix1, p1)

print "... end siteCustomize.py"
#-------------------------------------------------------------------------

I'd not like to use the current working directory instead of the
script directory, because the scripts may be started from anywhere
directories by specifying the path name in the invocation.

Does anyone have an idea?
    
Thank you in advance,
Peter



More information about the Python-list mailing list