Python modules can be imported into a script by providing their full file paths. This method allows you to load modules that may not be known in advance or are located outside of the standard library.
In Python 3.5 and above, use the importlib.util module:
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()
In Python 3.3 and 3.4, use SourceFileLoader from importlib.machinery:
from importlib.machinery import SourceFileLoader foo = SourceFileLoader("module.name", "/path/to/file.py").load_module() foo.MyClass()
For Python 2, use the imp module:
import imp foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass()
The above is the detailed content of How Can I Dynamically Import Python Modules Using Their Full File Paths?. For more information, please follow other related articles on the PHP Chinese website!