从动态导入模块内的父目录导入模块

2024-10-03 04:27:28 发布

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

我有这样的文件:

dir
 + main.py
 +--a
 |  +a.py
 |
 +--b
 |  +b.py
 |
 +--c
    +c.py

在{}我有

from b import b
funcs = b.loadAllFromC()
# some code which uses funcs

b.py中,我试图加载文件夹c中的所有模块,并在每个模块中获取函数,以便在main.py中使用:

import os
import importlib

def loadAllFromC():
    modules = []
    importlib.invalidate_caches()
    for file in os.listdir("./c/"):
        if file.endswith(".py"):
            module = importlib.import_module("c." + file[:-3])
            modules.append(module.getFunc())
    return modules

在{}中是这样的:

from a import a

def func():
    # code which uses something from a
def getFunc():
    return func

但是b.py中的module.getFunc()失败:

...
File "... /dir/c/c.py", line 1, in <module>
ModuleNotFoundError: No module named 'a'

当我尝试from ..a import a时,我得到了ValueError: attempted relative import beyond top-level package。 如何使用来自c.pya.py


Tags: frompyimportmoduleswhichmaindefdir