Add Module Directories for a Single Python Script

Sometimes it can be useful to have a Python script load modules from a different location than the normal installed library locations. Fortunately this can be accomplished by accessing the system path property.

The path property of the system module is nothing more than a list of directory locations Python scans to find modules when importing. If you want to use a nonstandard library, just use the append method to add the directory location where this module is stored.

Once this location is added to the list, any modules in it can be added. The functionality offered by these modules can then be used in your script.

Here is what the code looks like.

import sys
sys.path.append(r'<path to directory>')
import <custom module name>

The modification of the system path list property only persists while this particular script is running. No modification to the permanent list of locations scanned is made.

If you are like me and are curious what other locations your specific instance of Python is scanning, this can be discovered with a simple for loop to iterate through the items in the sys.path list.

import sys
for item in sys.path:
    print item

Reference: sys.path in Python Documentation