我正在尝试解析 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/