Home >Backend Development >Python Tutorial >How Can I Dynamically Import a Python Module Using Its Full Path?
Dynamically Importing a Module Given Its Full Path
In Python, it is possible to import a module without knowing its name in advance but only its full path. This functionality is useful in situations where modules are located in different directories or when the module name is dynamically generated.
Solution
There are several approaches to dynamically importing a module based on its full path:
Python 3.5 :
import importlib.util import sys # Define the full path to the module module_path = "/path/to/module.py" # Create a specification for the module spec = importlib.util.spec_from_file_location("module_name", module_path) # Create the module from the specification foo = importlib.util.module_from_spec(spec) # Add the module to the list of imported modules sys.modules["module_name"] = foo # Execute the module's code spec.loader.exec_module(foo) # Access a class from the imported module foo.MyClass()
Python 3.3 and 3.4:
from importlib.machinery import SourceFileLoader # Define the full path to the module module_path = "/path/to/module.py" # Create a SourceFileLoader object foo = SourceFileLoader("module_name", module_path).load_module() # Access a class from the imported module foo.MyClass()
Python 2:
import imp # Define the full path to the module module_path = "/path/to/module.py" # Import the module using imp.load_source() foo = imp.load_source('module_name', module_path) # Access a class from the imported module foo.MyClass()
Please note that these are not the only options, and other methods may be available depending on your specific needs and Python version.
The above is the detailed content of How Can I Dynamically Import a Python Module Using Its Full Path?. For more information, please follow other related articles on the PHP Chinese website!