动态加载和调用模块的Pythonic方法

2024-04-29 04:12:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个工作代码,但我想知道什么是正确的Python方法。你知道吗

我的目标是:有一个“插件”目录(每个插件一个模块),在程序运行时动态加载。所有模块都将定义一个函数,作为“入口点”。你知道吗

其目的是要有一个脚本,它可以通过一些额外的功能轻松地扩展。你知道吗

我得出的结论如下。reporter=本例中的plugin。你知道吗

import os
import importlib
import reporters  # Package, where plugins (reporters) will reside


def find_reporters():
    # Find all modules in directory "reporters" which look like "*_reporter.py"
    reporters = [rep.rsplit('.py', 1)[0] for rep in os.listdir('reporters') if rep.endswith('_reporter.py')]

    functions = []
    for reporter in reporters:
        module = importlib.import_module('.' + reporter, 'reporters')
        try:
            func = getattr(module, 'entry_function') # Read the entry_function if present
            functions.append(func) # Add the function to the list to be returned
        except AttributeError as e:
            print(e)

    return functions


def main():
    funcs = find_reporters()
    for func in funcs:
        func()  # Execute all collected functions

我对Python不太熟悉,所以这是一个可以接受的解决方案吗?你知道吗


Tags: 模块theinpyimport插件foros