How do I load a Python module given its full path?
Note that the file can be anywhere in the filesystem where the user has access rights.
See also: How to import a module given its name as string?
Advertisement
Answer
For Python 3.5+ use (docs):
JavaScript
x
8
1
import importlib.util
2
import sys
3
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
4
foo = importlib.util.module_from_spec(spec)
5
sys.modules["module.name"] = foo
6
spec.loader.exec_module(foo)
7
foo.MyClass()
8
For Python 3.3 and 3.4 use:
JavaScript
1
5
1
from importlib.machinery import SourceFileLoader
2
3
foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
4
foo.MyClass()
5
(Although this has been deprecated in Python 3.4.)
For Python 2 use:
JavaScript
1
5
1
import imp
2
3
foo = imp.load_source('module.name', '/path/to/file.py')
4
foo.MyClass()
5
There are equivalent convenience functions for compiled Python files and DLLs.
See also http://bugs.python.org/issue21436.