Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
什么是构造python3代码和导入的正确方法,可以同时用于测试和运行代码?_Python_Python 3.x_Python Import - Fatal编程技术网

什么是构造python3代码和导入的正确方法,可以同时用于测试和运行代码?

什么是构造python3代码和导入的正确方法,可以同时用于测试和运行代码?,python,python-3.x,python-import,Python,Python 3.x,Python Import,我对python比较陌生,我正在努力寻找一种文件层次结构和导入语句的组合,它们将在pycharm中工作,在命令行中运行pytest,在命令行中运行实际程序,并在bamboin中构建 以下是我的层次结构: foo | goo | __init__.py | run.py | koo | __init__.py | bar.py | loo | __init__.py | baz.py | tests | __init__.py | test_bar.py |

我对python比较陌生,我正在努力寻找一种文件层次结构和导入语句的组合,它们将在pycharm中工作,在命令行中运行pytest,在命令行中运行实际程序,并在bamboin中构建

以下是我的层次结构:

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'
然后所有测试都通过,但运行程序会出现以下错误:

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'
回溯(最近一次呼叫最后一次):
文件“goo/run.py”,第1行,在
将loo.baz导入为baz
文件“/home/me/PycharmProjects/foo/goo/loo/baz.py”,第1行,在
从古古进口酒吧
ModuleNotFoundError:没有名为“goo”的模块
类似,但没有明确的答案。一个发布的答案建议向下移动tests文件夹,但这在我们的构建服务器上造成了一个问题,而且这里的常见做法似乎是将测试放在顶层


假设我想将测试保持在顶级,是否有任何导入组合可以工作?

我会使用绝对导入组合,例如从goo.koo导入栏中导入
,并使用

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

然后对所有导入进行结构化,就像它们源自foo文件夹一样

这在从foo文件夹运行时起作用:PYTHONPATH=。python-goo/run.py。从foo文件夹中工作的另一个选项是python-mgoo.run。
export PYTHONPATH=$PYTHONPATH:/path/to/foo