The variable sys.path defines a list of folders searched for imported module files. It is built during the interpreter's initialisation, and can be also customised at run-time. It is important to know, how this list is built, and how we can add our own path to the list, to let our scripts find their modules.
First of all, this variable is initialised from the Windows environment variable PYTHONPATH. Both the Python interpreter itself and various other software systems using Python interpreter (e.g. Tribon M3), can define or update this variable accordingly, setting it to a list of paths separated by semi-colons.
Then, the special site module is imported. Note, that there is no need to issue the statement import site – Python interpreter will do this for you. This module is a standard Python module, which can be customised by the user to add specific changes to the environment, e.g. adding new folders to the sys.path list. By default (if you install a standalone Python interpreter), it adds some standard folders, like: '\Python23\lib\site-packages'.
Additionally, the site module searches the folders in the sys.path list for the *.pth files (path configuration files). If found, they are all read, and the paths defined therein are automatically added to the sys.path list, extending it. Such files are used by some Python packages, like e.g. wxPython, to define the location of the wxPython package modules.
Further system customisation can be placed in an optional sitecustomize module, which the site module attempts to import. Then, we can leave the site module unchanged, and put all the customisation in the sitecustomise module.
Finally, the module search path (sys.path) can be customised at run-time. Example:
path = 'E:\\PRIVATE\\MODULES'
import sys
if path not in sys.path:
sys.path.append(path)
import my_test_module
where the file my_test_module.py is located in the folder E:\PRIVATE\MODULES.
In the above example, the user-defined folder is placed at the end of the sys.path list. If you prefer to place it at the beginning of this list, just replace the statement:
sys.path.append(path)
No comments:
Post a Comment