Importing your own modules and setting the PYTHONPATH

Suppose you have written a python module with this path:
The file is a module which holds several useful function definitions, and you need to import it from other python programs.

Programs located in the same directory may import it like this:

import mymodule
i.e., use the filename without the .py extension. Of course, you might also use
from mymodule import ..
import mymodule as ..

Often however, you will need to import a module not located in the same directory as the main program. Continuing the example above, assume you're writing a program located in ~/PBI/ which needs to include

In order for the Python interpreter to find your module, you need to tell it where to look. You can do that by setting the environment variable PYTHONPATH. Depending on the shell program you use (e.g., xterm), this is done in one of two ways.


 export PYTHONPATH=${PYTHONPATH}:/users/[your username]/PBI/Modules/
C-shell (or tcsh, short for "Turbo C-shell"):
setenv PYTHONPATH ${PYTHONPATH}:/users/[your username]/PBI/Modules/
(You can learn which shell you use by typing "echo $0" in your xterm window.)

This means that you set PYTHONPATH to whatever it is already PLUS some more: i.e. you tell the interpreter to look for modules to import in whatever places it was looking already plus this cool new place.

Of course, you don't want to set the PYTHONPATH every time you need to import the module; you want it to be set automatically each time you log in. To fix that, do the following.

Bash: Create a file

and put the above line in it.

C-shell: Create a file

and put the above line in it.

Now you have a place to put things you want done every time you log in: just put it in this path.rc file.

If later you need to add another directory to the PYTHONPATH, you add it to the end of the existing line in the path.rc, like this:

setenv PYTHONPATH ${PYTHONPATH}:/users/[your username]/PBI/Modules/:[other directory path]
- you get the idea.