我的文件名为“ 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
编辑:
我的脚本最初被命名为“ 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
,则无法挽救您的生命)。