gpt4 book ai didi

python - ImportError : cannot import name, 即使我这里有所有解决方案

转载 作者:太空宇宙 更新时间:2023-11-03 20:17:17 29 4
gpt4 key购买 nike

我的文件名为“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 以清除以前执行的工件。但这些并不能消除早期错误的残余。

最佳答案

读取回溯:

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.

然而,这是一个丑陋的黑客行为。它可能会破坏其他东西(如果您有本地 sys.py,它也无法拯救您)。

关于python - ImportError : cannot import name, 即使我这里有所有解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58368532/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com