Wednesday, June 2, 2010

Python: Module search path



When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python


Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation- dependent default.

Now what if you have not specified PYTHONPATH during installation? How do I edit it?

Suppose, I have my module spam.py in ~/geekcode/python. I have my other program user.py that needs to the aforementioned module.

This module search path is comparable to CLASSPATH in java.

To add ~/geekcode/python to PYTHONPATH, in your interactive mode of the Python interpreter, edit the path variable in the sys module.

>>> import sys
>>> sys.path

Printing sys.path as shown above will show up your current PYTHONPATH.

This sys.path is just another mutable python list. Hence you can easily edit it using the usual list methods, here, the append method.

sys.path.append("/Users//geekcode/python")

The only drawback of this method is that, this setting is forgotten once you restart the interpreter. 

To persist this setting, you can use the '.pth' file.  A '.pth' file with any name like 'foobar.pth' can contain any number of newline separated list of paths you need to add to PYTHONPATH aka path aka sys.path variable. It is similar to .bash_profile or .profile files of Unix systems. The paths in .pth files are added automatically to the PYTHONPATH variable whenever the interpreter restarts.

All said, now the question is, "Where do I place this .pth file?". It can be placed in any path that is already mentioned in sys.path! EASY!

No comments:

Post a Comment