ImportError:即使我在这里有所有解决方案,也无法导入名称

问题描述 投票:0回答:1

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

python random import
1个回答
0
投票
阅读回溯:

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,则无法挽救您的生命)。
© www.soinside.com 2019 - 2024. All rights reserved.