相对导入会引发ValueError

时间:2018-07-14 02:53:43

标签: python python-3.x import

我具有以下项目结构(使用python 3.6):

Project
|  scripts
|  |  module.py
|  tests
|  |  test.py

module.py包含一个名为Class1的类。

test.py具有以下代码:

from .. scripts.module.py import Class1

但是,当我运行test.py时,出现以下错误:

ValueError: attempted relative import beyond top-level package

该如何解决?为什么相对导入无效?

该帖子可能会被标记为重复,但我要么无法理解到目前为止所看到的帖子,要么这些帖子不能反映我的情况。

编辑: 我看了一些python Github存储库,它们在他们的测试代码中都做类似import scripts.module的事情。这是如何运作的??我是否需要其他文件才能像这样连接我的项目?

这是我查看过的Github存储库。我要说的是位于测试文件夹中:https://github.com/AtsushiSakai/PythonRoboticshttps://github.com/nbedos/termtosvg

1 个答案:

答案 0 :(得分:1)

在这里回答我自己的问题:

显然,在运行python脚本时,如果不修改sys.pathSource,请参见案例4),就无法在脚本所在目录上方导入任何内容。正在运行脚本的程序包被视为顶级模块。如果是正在运行的脚本,那么您将无法超越。

当然,有解决方法:

解决方案:

  1. 修改sys.path。这是我发现的最佳方法(鉴于上面的文件目录结构,您可能会有不同数量的句点):

    import sys.path
    sys.path.append('.')
    
    from scripts.module import Class1
    
  2. 从上面的脚本运行模块。例如,我将文件目录更改为:

    Project
    |  main.py
    |  scripts
    |  |  module.py
    |  tests
    |  |  test.py
    

    main.py中,我将输入:

    import tests.test.py
    

    我在test.py中可能有以下内容,但仍然可以解决:

    from scripts.module import Class1
    
  3. test.py中与#2具有相同的功能,但从命令提示符处运行它:

    cd ...\Project
    python
    >>> import tests.test
    >>> # do what you need