How to get the module path and use it in your program

Get module path

We need to put our code into proper folders in order to let Python to find it.

Basically we have two ways to add our code to Python system path.

  1. Putting Your Module in the Right Place
  2. Telling the Python Where to Look

Putting Your Module in the Right Place

A list of search directories can be found in the path variable in the sys module.


import sys, pprint 
pprint.pprint(sys.path) 

The list provides a place to put modules if you want Python to find them. As long as your module is located in a place like site-packages, all your programs will be able to import it.

Telling the Python Where to Look

The standard method is to include your module directory (or directories) in the environment variable PYTHONPATH.

In UNIX, we can add the directory ~/YourPython to your PYTHONPATH:


export PYTHONPATH=$PYTHONPATH:~/YourPython 

For windows, we can execute the following


set PYTHONPATH=%PYTHONPATH%;C:\python 

The following code add our path to the system path list.


import sys 
sys.path.append('c:/python') 

The file that contains the code of a module must be given the same name as the module with an additional .py file name extension.

In Windows, you can use the file name extension .pyw instead.





















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module