【问题标题】:ImportError: cannot import name, even though I've every solution hereImportError:无法导入名称,即使我在这里有所有解决方案
【发布时间】:2019-10-13 23:17:39
【问题描述】:

我的文件名为“foo.py”。它只有两行。

import random
print(random.randint(10))

错误是……

    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 45, in <module>
    from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
  File "math.py", line 2, in <module>
    from random import randint
ImportError: cannot import name randint
  1. 我使用的是 MacOS 10.14.6
  2. 我注意到我没有在这个脚本中调用 random.randint(),甚至 虽然它出现在错误文本中。
  3. 我用 $python 运行脚本
  4. 我的 /usr/bin/python 链接到 python 2.7
  5. 我也用 python 3 试过这个,同样的错误。

编辑:

我的脚本最初命名为“math.py”,但我更改了它以响应另一个解决方案,该解决方案指出与 math.py 库的名称冲突(即使我的脚本没有导入该库)。即使在我的脚本名称更改后,我仍然看到 --File "math.py"-- 错误。即使我不再使用 random.randint(),我仍然看到我的错误中引用了该函数。

我尝试删除 random.pyc 和 math.pyc 以清除以前执行的工件。但这些并不能消除早期错误的残余。

【问题讨论】:

  • 您似乎有一个名为 math.py 的文件,随机模块试图通过内置数学模块导入该文件?如果是这种情况,请将此模块重命名为其他名称。
  • 只是想确保您知道对 2.x 的支持将于今年年底正式结束。

标签: python random import


【解决方案1】:

阅读回溯:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py"

Python 试图在标准库 random 模块中做一些事情...

from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil

特别是它会尝试导入标准库math 模块...

File "math.py", line 2, in <module>

但它会得到你的(注意这次文件名上没有路径;它只是当前目录中的math.py);即您开始的脚本。 Python 检测到循环导入并失败:

ImportError: cannot import name randint

其实用randint也无所谓,因为这是模块实际导入的问题。

发生这种情况是因为默认情况下 Python 被配置(使用sys.path,这是一个要尝试的路径列表,按顺序)尝试从当前工作目录导入脚本,然后再查看其他任何地方。当你只想在同一个文件夹中编写几个源文件并让它们相互工作时很方便,但它会导致这些问题。

预期的解决方案是重命名您的文件。不幸的是,没有要避免的明显名称列表,尽管您可以查看您的安装文件夹以确定(或者只是查看在线library reference,尽管这不是那么直接)。

你也可以修改 sys.path:

import sys
sys.path.remove('') # the empty string in this list is for the current directory
sys.path.append('') # put it back, at the end this time
import random # now Python will look for modules in the standard library first,
# and only in the current folder as a last resort.

但是,这是一个丑陋的 hack。它可能会破坏其他东西(如果您有本地 sys.py,它无法拯救您)。

【讨论】:

    猜你喜欢
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 2014-09-20
    相关资源
    最近更新 更多