Skip to main content
 首页 » 编程设计

python之构建适用于测试和运行代码的 python3 代码和导入的正确方法是什么

2024年11月24日12jackei

我是 python 的新手,我正在努力寻找文件层次结构和导入语句的组合,它们可以在 pycharm 中工作,在命令行上运行 pytest,在命令行上运行实际程序,并在 bamboo 中构建。

这是我的层次结构:

foo 
| goo 
| __init__.py 
| run.py 
  | koo 
    | __init__.py 
    | bar.py 
  | loo 
    | __init__.py 
    | baz.py 
| tests 
| __init__.py 
| test_bar.py 
| test_baz.py 
| test_file.py 
| data 
  | text.txt 

这是我的代码:

foo/goo/koo/bar.py:

greeting = "hello" 
 
 
def hello(): 
    return greeting 

foo/goo/loo/baz.py:

from koo import bar 
 
 
def greet(): 
    return "the greeting is..." + bar.hello() 

foo/goo/run.py:

import loo.baz as baz 
 
 
print(baz.greet()) 

foo/tests/test_bar.py:

import goo.koo.bar as b 
 
 
def test_hello(): 
    assert b.hello() == "hello" 

foo/tests/test_baz.py:

import goo.loo.baz as b 
 
 
def test_greet(): 
    assert b.greet() == "the greeting is...hello" 

foo/tests/test_file.py:

import os.path 
import sys 
 
 
def test_file(): 
    f = open(os.path.join(sys.path[0], "tests", "data", "test.txt"), "rt") 
    assert f.read() == "hello world" 

当我进入 foo 目录并运行时

python goo/run.py 

这行得通。但是当我运行时

python -m pytest tests 

我得到了错误

Traceback: 
tests/test_baz.py:1: in <module> 
    import goo.loo.baz as b 
goo/loo/baz.py:1: in <module> 
    from koo import bar 
E   ModuleNotFoundError: No module named 'koo' 

如果我将 baz.py 更改为以下内容:

from goo.koo import bar 
 
 
def greet(): 
    return "the greeting is..." + bar.hello() 

然后所有的测试都通过了,但是运行程序会出现这个错误:

Traceback (most recent call last): 
  File "goo/run.py", line 1, in <module> 
    import loo.baz as baz 
  File "/home/me/PycharmProjects/foo/goo/loo/baz.py", line 1, in <module> 
    from goo.koo import bar 
ModuleNotFoundError: No module named 'goo' 

This question类似,但没有明确的答案。一个已发布的答案建议将测试文件夹向下移动,但这会导致我们的构建服务器出现问题,而且这里的常见做法似乎是将测试放在顶层。

假设我想将测试保持在顶层,是否可以使用任何导入组合?

请您参考如下方法:

我会使用绝对导入的组合,例如from goo.koo import bar 并将文件夹 foo 添加到您的 PYTHONPATH 中

export PYTHONPATH=$PYTHONPATH:/path/to/foo 

然后将所有导入结构化,就好像它们来自 foo 文件夹一样