试图使路径工作 - 尝试相对导入超出顶级包

Geo*_*rge 6 python pytest

我不能做这个工作..

我的结构是:

program_name/

  __init__.py
  setup.py

  src/
    __init__.py

    Process/
        __init__.py
        thefile.py

  tests/
     __init__.py
     thetest.py
Run Code Online (Sandbox Code Playgroud)

thetest.py:

from ..src.Process.thefile.py import sth
Run Code Online (Sandbox Code Playgroud)

跑步:pytest ./tests/thetest.pyprogram_name给出:

ValueError: attempted relative import beyond top-level package

我也试过其他方法,但我收到各种错误.

但我希望以上工作能够奏效.

Nab*_*med 8

ValueError:在非包中尝试相对导入

您正尝试在模块中使用相对导入的状态,这些状态将用于包,即使其成为包添加__init__.pythetest.py从包外的某个文件调用.直接thetest.py从解释器运行将无法正常工作.

相对导入要求使用它们的模块本身作为包模块导入.


建议1:

当前tests目录有一个__init__.py文件,但是不允许你将它作为模块运行(通过shell) - 为了使你当前(相对)导入工作,你需要在外部(到包)文件/模块中导入它 -让我们创建一个main.py(可以任意命名):

    main.py
    program_name/
      __init__.py
      setup.py
      src/
        __init__.py
        Process/
            __init__.py
            thefile.py
      tests/
         __init__.py
         thetest.py
Run Code Online (Sandbox Code Playgroud)

src/Process/thefile.py:

s = 'Hello world'
Run Code Online (Sandbox Code Playgroud)

tests/thetest.py:

from ..src.Process.thefile import s

print s
Run Code Online (Sandbox Code Playgroud)

main.py:

from program_name.tests.thetest import s
Run Code Online (Sandbox Code Playgroud)

执行main.py:

[nahmed@localhost ~]$ python main.py 
Hello world
Run Code Online (Sandbox Code Playgroud)

建议2:

执行文件正好在根目录上方,即以一个级别向上program_name/,以下列方式:

[nahmed@localhost ~]$ python -m program_name.tests.thetest
Hell World
Run Code Online (Sandbox Code Playgroud)

PS.相对导入用于包,而不是模块.


Yib*_*ibo 6

刚刚通过大量谷歌搜索解决了类似的问题。这是不改变现有文件结构的两种解决方案:

1

从父文件夹导入模块的方式from ..src.Process.thefile.py import sth称为“相对导入”。

仅当从顶级包作为包启动时才支持它。在您的情况下,即从包含program_name/并键入的目录启动命令行(对于 win 环境)

python -m program_name.tests.thetest
Run Code Online (Sandbox Code Playgroud)

2

否则——当尝试单独运行脚本或从非顶级包运行脚本时——您可以在运行时手动将目录添加到 PYTHONPATH。

import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from src.Process.thefile import s
Run Code Online (Sandbox Code Playgroud)

首先尝试第一个,看看它是否与pytest框架兼容。否则第二个应该总是解决问题。

参考(即使使用 __init__.py 也如何修复“在非包中尝试相对导入”