Importing Python Modules Dynamically by File Path
Python offers various methods for importing modules based on their full path, enabling access to modules located anywhere within the filesystem with appropriate permissions.
Python 3.5 and Above
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()
Python 3.3 and 3.4
from importlib.machinery import SourceFileLoader foo = SourceFileLoader("module.name", "/path/to/file.py").load_module() foo.MyClass()
Python 2
import imp foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass()
These methods allow for dynamic module loading based on the specified file path. They are particularly useful when dealing with modules that are not part of the standard Python distribution or are located in custom directories.
The above is the detailed content of How Can I Dynamically Import Python Modules by File Path?. For more information, please follow other related articles on the PHP Chinese website!