相对路径的依赖项的模块

相对路径的依赖项的模块

本文介绍了如何使用imp导入具有相同绝对/相对路径的依赖项的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用带有imp的绝对/相对路径在同一目录中导入具有依赖项的模块?

Is there a way to import modules with dependencies within the same directory using an absolute/relative path with "imp" ?

以下是目录结构:

.
├── importFrom
│   ├── dependant.py
│   └── dependence.py
└── test.py

文件test.py使用以下方式导入dependant.py:

file test.py imports dependant.py using:

modname=imp.load_source("testImp","importFrom/dependant.py")

其中依次导入依赖.py:

which in turn imports dependence.py direcly with:

import dependence

调用test.py给出

Calling test.py gives

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    modname=imp.load_source("testImp","importFrom/dependant.py")
  File "importFrom/dependant.py", line 1, in <module>
    import dependence
ImportError: No module named dependence

这可能是值得的让load_source将加载模块的路径添加到加载器,以便它自动找到它的相对依赖关系。
现在我发现的唯一选择是添加到系统路径,放入test.py

It may be worthwhile to have load_source add the path to the loaded module to the loader so that it finds its relative dependencies automatically.For now the only alternative I've found is adding to the system path, putting into test.py

编辑:我找到了一个更好的方法使用路径进行相对导入,添加文件以获取调用者的绝对路径(与当前工作目录无关)

I've found a better way to do the relative import with path, added file to get the absolute path of the caller (independence from current working directory)

sys.path.append(os.path.join(os.path.dirname(__file__), 'importFrom'))
import dependant


推荐答案

IMO使用 load_source 这是不可行的做必要的事情,以便你的'dependant.py'文件中的导入考虑其父目录。

IMO this is not feasible with load_source which doesn't do necessary things so that import in your 'dependant.py' file consider its parent directory.

你应该做所建议的事情( __ init__目录中的.py 和模块中的绝对导入),或者使用较低级别的find_module / load_module函数,它们允许这类事情(参见find_module'path'参数)

You should either do what have been suggested (__init__.py in the directory and absolute import in the module), or use lower-level find_module / load_module functions which allows this kind of things (see find_module 'path' argument)

这篇关于如何使用imp导入具有相同绝对/相对路径的依赖项的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 14:34