Skip to main content
 首页 » 编程设计

python之从 Python 2.7 中的父目录导入模块

2025年02月15日7落叶无声

我无法从 2.7 中的父目录导入模块,我不确定为什么。任何帮助将不胜感激。

目录结构

我有一个具有以下目录结构的 Python 包:

source/ 
|--foo/__init__.py 
|--foo/bar/__init__.py 
|--foo/bar/nested.py 
|--foo/top.py 
tests/ 
|--helpers/__init__.py 
|--foo/__init__.py 
|--foo/bar/__init__.py 
|--foo/bar/nested_test.py 
|--foo/top_test.py 
setup.py 
setup.cfg 
tox.ini 

配置

我几乎交替使用 pytest 和 python setup.py test 来运行我的测试。在 tox.ini 中,我有:

[tox] 
envlist = py27 
 
[testenv] 
commands = pytest 
deps = pytest 
 
[pytest] 
testpaths=tests 

请注意,我实际上并没有使用 tox 来运行我的测试。

在 setup.cfg 中:

[aliases] 
test=pytest 

我不是 100% 确定,但我认为这个设置意味着当我运行 python setup.py test 时,它实际上只是运行 pytest,所以它 < em>可能与这个问题无关。

问题

在 foo/top_test.py 中,我可以import tests.helpers,但是在 foo/bar/nested_test.py 中,同样import 引发了一个 ImportError 表示找不到该模块。

为什么会这样,我该如何解决?

尝试

在运行 pip install pytest 和 后,我尝试在干净的 virtualenv 中运行 pytest 和 python setup.py test pip install -r requirements.txt(我的 requirements.txt 基本上是一个空白文件,-e 和 -i 设置为私有(private)仓库。

注意:我可以从项目的根目录打开一个 python REPL 并 import tests._helper 没有任何问题。

我还尝试将 tests 和 tests.helpers 添加到 setuptools.setup() 中的 tests_require 参数 函数在 setup.py 中,但看起来它试图从远程索引安装那些而不是使用本地模块。

我还尝试在我的 foo/bar/nested_test.py 中附加到 sys.path:

import os 
import sys 
 
sys.path.append(os.path.realpath('tests')) 

其他说明

  • 我不愿意将我的测试捆绑到每个包的源目录中
  • 我现在无法使用 python 3

请您参考如下方法:

我注意到的一件事是您似乎没有tests/__init__.py。不确定这对您的情况是否重要,但在下面的示例中确实如此。

每当我遇到这样的问题时,我都会尝试用尽可能少的东西设置一个简化的测试用例。获取 setuptools、pytest 和所有其他杂音,只需调试模块结构,然后在确定结构合理后将它们添加回去。

例如,这是一个脚本

#!/bin/bash 
rm -rf tests 
mkdir -p tests/foo/bar 
mkdir -p tests/helpers 
touch tests/__init__.py 
touch tests/foo/__init__.py 
touch tests/foo/bar/__init__.py 
touch tests/helpers/__init__.py 
echo 'import tests.helpers' > tests/foo/top_test.py 
echo 'import tests.helpers' > tests/foo/bar/nested_test.py 
tree tests 
python -c 'import tests.foo.bar.nested_test; print "got here"' 

产生输出

tests 
|-- __init__.py 
|-- foo 
|   |-- __init__.py 
|   |-- bar 
|   |   |-- __init__.py 
|   |   `-- nested_test.py 
|   `-- top_test.py 
`-- helpers 
    `-- __init__.py 
 
3 directories, 6 files 
got here 

一旦有了像这样的简单脚本,您就可以交互式地试验您的导入。