尝试使路径工作 - 尝试在顶级包之外进行相对导入 [英] trying to make paths work - attempted relative import beyond top-level package

查看:43
本文介绍了尝试使路径工作 - 尝试在顶级包之外进行相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法完成这项工作..

I can't make this work..

我的结构是:

program_name/

  __init__.py
  setup.py

  src/
    __init__.py

    Process/
        __init__.py
        thefile.py

  tests/
     __init__.py
     thetest.py

thetest.py:

thetest.py:

from ..src.Process.thefile.py import sth

运行:pytest ./tests/thetest.py 来自 program_name 给出:

Running: pytest ./tests/thetest.py from program_name gives :

ValueError: 试图在顶级包之外进行相对导入

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

I tried also other approaches but i am receiving various errors.

但我希望上述方法能奏效.

But I would expect for the above to work.

推荐答案

ValueError: Attempted relative import in non-package

声明您正在尝试在模块中使用相对导入,这些模块将用于包,即使其成为包添加 __init__.py 并调用 thetest.py 来自包外的某个文件.直接从解释器运行 thetest.py 将不起作用.

States that you're trying to use relative import in the module, which are to be used for packages i.e. to make it a package add __init__.py and call the thetest.py from some file outside the package. Directly running thetest.py from interpreter won't work.

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

Relative imports require that the module which uses them is being imported itself either as package module.

<小时>

建议 1:

当前的 tests 目录有一个 __init__.py 文件,但这不允许您将其作为模块(通过 shell)运行 - 使您当前的 (相对)导入工作,您需要将其导入到外部(打包)文件/模块中 - 让我们创建一个 main.py(可以将其命名为您喜欢的任何名称):

The current tests directory has a __init__.py file but that doesn't allow you to run it as a module (via shell) - to make your current (relative) import work, you need to import it in an external (to package) file/module - let's create a main.py (can name it anything you like):

    main.py
    program_name/
      __init__.py
      setup.py
      src/
        __init__.py
        Process/
            __init__.py
            thefile.py
      tests/
         __init__.py
         thetest.py

src/Process/thefile.py:

src/Process/thefile.py:

s = 'Hello world'

tests/thetest.py:

from ..src.Process.thefile import s

print s

ma​​in.py:

from program_name.tests.thetest import s

执行ma​​in.py:

[nahmed@localhost ~]$ python main.py 
Hello world

<小时>

建议 2:

以以下方式执行根目录正上方的文件,即在 program_name/ 上一级:

Execute the file just above root dir i.e. one level up the program_name/ , in the following fashion:

[nahmed@localhost ~]$ python -m program_name.tests.thetest
Hell World

<小时>

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


P.S. relative imports are for packages, not modules.

这篇关于尝试使路径工作 - 尝试在顶级包之外进行相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆