python - 在路径中加载每个 .py 文件 - imp.load_module 提示相对导入

标签 python import

我正在尝试解析 python 源文件的给定路径,将每个文件和 DoStuff™ 导入每个导入的模块。

def ParsePath(path):
    for root, dirs, files in os.walk(path):
        for source in (s for s in files if s.endswith(".py")):
            name = os.path.splitext(os.path.basename(source))[0]
            m = imp.load_module(name, *imp.find_module(name, [root]))
            DoStuff(m)

上述代码有效,但无法识别包 ValueError: Attempted relative import in non-package

我的问题基本上是,如何告诉 imp.load_module 给定模块是包的一部分?

最佳答案

您不能直接告诉 Importer Protocol 方法 load_module 给定的模块是包的一部分。取自PEP 302 New Import Hooks

The built-in __import__ function (known as PyImport_ImportModuleEx in import.c) will then check to see whether the module doing the import is a package or a submodule of a package. If it is indeed a (submodule of a) package, it first tries to do the import relative to the package (the parent package for a submodule). For example if a package named "spam" does "import eggs", it will first look for a module named "spam.eggs". If that fails, the import continues as an absolute import: it will look for a module named "eggs". Dotted name imports work pretty much the same: if package "spam" does "import eggs.bacon" (and "spam.eggs" exists and is itself a package), "spam.eggs.bacon" is tried. If that fails "eggs.bacon" is tried. (There are more subtleties that are not described here, but these are not relevant for implementers of the Importer Protocol.)

Deeper down in the mechanism, a dotted name import is split up by its components. For "import spam.ham", first an "import spam" is done, and only when that succeeds is "ham" imported as a submodule of "spam".

The Importer Protocol operates at this level of individual imports. By the time an importer gets a request for "spam.ham", module "spam" has already been imported.

然后您必须模拟内置导入的作用并在加载子模块之前加载父包。

关于python - 在路径中加载每个 .py 文件 - imp.load_module 提示相对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4907054/

相关文章:

flutter - 如何跨 Flutter 移动、网络和窗口添加条件导入?

ms-access - 将 VBScript 常规日期时间导入 MS Access 日期/时间列

Python:访问另一个文件中的函数中的变量

python - 类型错误 : 'module' object is not callable for python object

python - 从简单的 pandas 数据帧创建矩阵

python - 如何在Python中访问字典中的某个列表条目?

python - FROM random IMPORT* 和 IMPORT random 有什么区别? (随机()和随机范围())

java - 使用ant命令行添加jar文件在java项目中添加类

python - 在 Azure Databricks 上运行 Bokeh 服务器?

python - 无法通过 ftplib (Python) 使用 IP 地址