In Python, most modules can be imported using their names as strings. However, there are scenarios where it may be necessary to import a module based on its absolute path. Here's a comprehensive guide to dynamically importing a module given its full path:
import importlib.util import sys # Specify the module name and its full path module_name = "module.name" file_path = "/path/to/file.py" # Create a specification for the module spec = importlib.util.spec_from_file_location(module_name, file_path) # Create the module object using the specification module = importlib.util.module_from_spec(spec) # Add the module to the system's module list sys.modules[module_name] = module # Execute the module's code spec.loader.exec_module(module) # Access the imported classes or functions module.MyClass()
from importlib.machinery import SourceFileLoader # Specify the module name and its full path module_name = "module.name" file_path = "/path/to/file.py" # Load the module using the SourceFileLoader module = SourceFileLoader(module_name, file_path).load_module() # Access the imported classes or functions module.MyClass()
import imp # Specify the module name and its full path module_name = "module.name" file_path = "/path/to/file.py" # Load the module using imp.load_source module = imp.load_source(module_name, file_path) # Access the imported classes or functions module.MyClass()
The above is the detailed content of How to Dynamically Import a Python Module Using Its Full Path?. For more information, please follow other related articles on the PHP Chinese website!