Import python module NOT on path

One way is to simply amend your path:

import sys
sys.path.append('C:/full/path')
from foo import util,bar

Note that this requires foo to be a python package, i.e. contain a __init__.py file. If you don’t want to modify sys.path, you can also modify the PYTHONPATH environment variable or install the module on your system. Beware that this means that other directories or .py files in that directory may be loaded inadvertently.

Therefore, you may want to use imp.load_source instead. It needs the filename, not a directory (to a file which the current user is allowed to read):

import imp
util = imp.load_source('util', 'C:/full/path/foo/util.py')

Leave a Comment