【问题标题】:Spyder not handling relative importsSpyder 不处理相对进口
【发布时间】:2018-12-05 18:19:35
【问题描述】:

我正在尝试用 python3 证明我的工作,而 spyder 似乎与 absolute_import 存在问题。

出于演示目的,我创建了两个简单的文件。 callercallme

调用者

from __future__ import absolute_import
from .callme import helloWorld

def runme(msg):
    helloWorld(msg)


if __name__ == "__main__":

    runme('It worked!')

给我打电话

def helloWorld(msg):      
    print("helloWorld's message is '{}'".format(msg))


if __name__ == "__main__":

    helloWorld('Hi')

尝试从 spyder 运行 caller 时,出现以下错误:

ValueError: Attempted relative import in non-package

通过 anaconda 提示符(python 2)从 ipython 运行或从 jupyter notebook(运行 python3 或 python2)运行都可以正常工作。

关于如何修复 spyder 的行为以便正确识别 absolute_import 的想法?

尝试过的 Spyder 版本:

  • 3.2.4 Python 2.7.14 64 位、Qt 5.6.2、Windows 10 上的 PyQt5 5.6

  • 3.3.2 Python 2.7.14 64 位 | Qt 5.6.2 | PyQt5 5.6 | Windows 10

更新

通过conda update spyder(现在是 3.3.2 版)更新 spyder 并没有解决问题。

【问题讨论】:

    标签: spyder


    【解决方案1】:

    如果您在系统终端中运行python caller.py,您将得到与您发布的完全相同的错误,即

    ValueError: Attempted relative import in non-package
    

    所以这不是 Spyder 的问题(因为当您使用 Run > Run 执行文件时,Spyder 运行类似于 python caller.py 的东西),但相对导入的工作方式。

    请参阅此答案以获得正确的解释:

    https://stackoverflow.com/a/11537218/438386

    本质上,您不能在脚本中使用相对导入。


    注意:有一种解决方法可以避免此错误,如本答案所述:

    https://stackoverflow.com/a/11536794/438386

    但是,抱歉,我们无法在 Spyder 中将脚本作为包执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-23
      • 2023-03-08
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2020-08-28
      相关资源
      最近更新 更多