module search path

Jeff Epler jepler at unpythonic.net
Sat Jul 31 12:53:56 EDT 2004


... because ".." is relative to os.getcwd(), and the httpd doesn't
change to the user directory before starting the cgi script?

os.dirname(__file__) should tell you the directory where the current
module resides, as would sys.argv[0]:

    $ cat /tmp/ajay.py 
    print __file__
    import sys
    print sys.argv[0]
    $ python /tmp/ajay.py 
    /tmp/ajay.py
    /tmp/ajay.py

So you could write something like
    # near the top of index.cgi
    cgidir = dirname(__file__)
    commondir = os.path.join(cgidir, os.pardir, "common")
    sys.path.append(commondir)
    import utils
or you might be able to change the the directory where the cgi script
resides:
    os.chdir(cgidir)
    sys.path.append(os.pardir)
    import common.utils
if you prefer.

Anyway, __file__ is the trick you need to know about.  It is documented:
    http://docs.python.org/ref/types.html#l2h-106
.. but maybe not where you looked for it, if you even suspected it
existed.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040731/9a91698b/attachment.sig>


More information about the Python-list mailing list