setting PYTHONPATH

Terry Hancock hancock at anansispaceworks.com
Mon Mar 6 16:01:35 EST 2006


On Sun, 5 Mar 2006 23:05:31 -0800 (PST)
anushya beauty <abbi_0382 at yahoo.com> wrote:
>       Anybody, please help me to set PYTHONPATH to import
>       my modules?. Where is sy.path set?
>   
>   In some python groups site, to import the user modules,
>   they explained  to  create one __init__.py file in my
>   module directory (this file  should include __all__
>   variable, which refer to the modules that the  user
>   wants to import). How to set the __all__ var?

PYTHONPATH
   is an environment variable. You set this however your
   operating system lets you do handle them. In Linux or
   Unix with csh/tcsh, this looks like:

   setenv PYTHONPATH /path/to/python/files

   in bash/sh it looks like:

   set PYTHONPATH=/path/to/python/files

   and I'm sure there's some way to do it in Windows and
   OS X.

sys.path
   means "the name path in the module sys"  So, in order to
   see that, you need to (from python):

>>> import sys
>>> sys.path
>>> sys.path
['', '/usr/lib/python23.zip', '/usr/lib/python2.3',
'/usr/lib/python2.3/plat-linux2', ...]

    As you can see, it's a list.  You can append to it, or
    more likely, prepend the directory you need.

__all__
   is a "magic" variable in the __init__.py (or any
   module) which you can set to define which names will
   be imported when you import from that module:

If module "foo.py" contains:
 
__all__ = ['a', 'b']
a = 1
b = 2
c = 3

then another module which imports from foo will get
a and b, but not c:

>>> from foo import *
>>> a,b
(1, 2)
>>> c
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'c' is not defined

Meanwhile:

__init__.py
     This is how you make a "package" out of a directory of
     python modules. Its namespace is the package-wide
     space. So you can control what modules are loaded with
     explicit commands, or you can leave it empty and then
     you will have to do explicit imports of sub-modules:

spam/
   __init__.py
   ham.py
   eggs.py

     requires explicit imports of ham and eggs modules:

>>> import spam
>>> import spam.ham
>>> import spam.eggs

Although these things are all interesting, they are not
closely related, and you haven't really said what your
problem is, so I don't know which is going to be helpful to
you.




-- 
Terry Hancock (hancock at AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com




More information about the Python-list mailing list