Home > Backend Development > Python Tutorial > How to Dynamically Import a Python Module Using Its Full Path?

How to Dynamically Import a Python Module Using Its Full Path?

Linda Hamilton
Release: 2025-01-01 01:57:09
Original
992 people have browsed it

How to Dynamically Import a Python Module Using Its Full Path?

Dynamically Importing a Module Using its Full Path

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:

Python 3.5

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()
Copy after login

Python 3.3 and 3.4

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()
Copy after login

Python 2

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template