how do I import from other directories?

Harry George hgg9140 at cola2.ca.boeing.com
Tue Dec 17 14:48:40 EST 2002


"Fredrik Lundh" <fredrik at pythonware.com> writes:

> Peter Rams wrote:
> 
> > > Suppose your personal modules are in /home/me/pymodules
> > >
> > > import sys
> > > sys.path.append('/home/me/pymodules')
> > > import mymodule
> > > ...
> >
> > thanks for the answer, but that's what I wanted to avoid because I run my
> > script on the webserver of my provider and I don't know if it's possible to
> > change the path there... is there another possibility? Or should it always
> > be possible to change the path on a foreign websever?
> 
> sys.path is a Python list, and can be manipulated from inside the
> script just like any other list.
> 
> </F>
> 
> 

Working with sys.path, you can append or prepend:
   sys.path.append('/my/full/path')
   sys.path.insert(0,'my/full/path')

You can use relative paths, e.g., to navigate inside a tree of
related scripts:
   sys.path.insert(0,'../../my/local/path')

However, all attempts to modify sys.path internally are troublesome
because they may not work if you try to run the code different places
(e.g., in a beta test site).  An alternative is to use a small script
which sets PYTHONPATH:

  my_beta_script.sh:
    #!/bin/sh
    export PYTHONPATH=/my/beta/path
    /usr/local/bin/python my_script.py
  my_prod_script.sh:
    #!/bin/sh
    export PYTHONPATH=/my/prod/path
    /usr/local/bin/python my_script.py

This approach is handy in general, e.g., for pointing to special
libraries, setting commandline args, etc.:

  my_test_script.sh:
    #!/bin/sh
    PY=/usr/local/bin/python2.2.2
    export PYTHONPATH=/my/beta/path:/path/to/pygtk
    export LD_LIBRARY_PATH=/path/to/pgsql/libs:${LD_LIBRARY_PATH}
    MYFILE=test/testdata/blah
    ${PY} my_script.py -d ${MYFILE}.txt > ${MYFILE}.xml

This approach puts extra overhead on the startup, but in many cases
(infrequent use; long compute processes in the working script), that
is ok.  I use it for cgi's too, where I need it and those
characteristics apply.



-- 
harry.g.george at boeing.com
6-6M31 Knowledge Management
Phone: (425) 294-8757



More information about the Python-list mailing list