snippetpythonCritical
How can I import a module dynamically given the full path?
Viewed 0 times
howdynamicallytheimportgivenpathcanmodulefull
Problem
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?
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?
Solution
Let's have
For Python 3.5+ use (docs):
For Python 3.3 and 3.4 use:
(Although this has been deprecated in Python 3.4.)
For Python 2 use:
There are equivalent convenience functions for compiled Python files and DLLs.
See also http://bugs.python.org/issue21436.
MyClass in module.name module defined at /path/to/file.py. Below is how we import MyClass from this moduleFor Python 3.5+ use (docs):
import importlib.util
import sys
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = foo
spec.loader.exec_module(foo)
foo.MyClass()For Python 3.3 and 3.4 use:
from importlib.machinery import SourceFileLoader
foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()(Although this has been deprecated in Python 3.4.)
For Python 2 use:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()There are equivalent convenience functions for compiled Python files and DLLs.
See also http://bugs.python.org/issue21436.
Code Snippets
import importlib.util
import sys
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = foo
spec.loader.exec_module(foo)
foo.MyClass()from importlib.machinery import SourceFileLoader
foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()Context
Stack Overflow Q#67631, score: 1819
Revisions (0)
No revisions yet.