什么是“坏魔法数字”ImportError在python,我如何解决它?

我能在网上找到的唯一一件事表明,这是由编译一个.py -> .pyc文件引起的,然后试图使用错误版本的python。然而,在我的例子中,文件有时似乎导入得很好,但有时却不行,我不知道为什么。

python在回溯中提供的信息不是特别有用(这就是为什么我在这里问…),但如果它有帮助的话,它在这里:

Traceback (most recent call last):
  File "run.py", line 7, in <module>
    from Normalization import Normalizer

当前回答

如果您手动以.pyc扩展名命名文件,也会发生“坏魔术数字”错误

其他回答

在我的情况下,我已经克隆了一个库的解释器

#!/usr/bin/env python

虽然python指向Python2.7,但我的主要代码是使用python3.6运行的……它仍然创建了一个*。Pyc文件2.7版本…

我可以说这个错误可能是2.7和3+版本混合的结果,这就是为什么清理(以任何你能想到的你正在使用的方式)在这里会有帮助…

别忘了调整那些Python2x代码-> python 3…

您需要在环境中的每个路径上运行此命令。

>>> import sys
>>> sys.path
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/source_code/src/python', '/usr/lib/python3/dist-packages']

然后在这里的每个目录下运行命令

find /usr/lib/python3.6/ -name "*.pyc" -delete
find /usr/local/lib/python3.6/dist-packages -name "*.pyc" -delete
# etc...

加载一个python3生成的*。带有python2的Pyc文件也会导致此错误。

如果您手动以.pyc扩展名命名文件,也会发生“坏魔术数字”错误

I had a strange case of Bad Magic Number error using a very old (1.5.2) implementation. I generated a .pyo file and that triggered the error. Bizarrely, the problem was solved by changing the name of the module. The offending name was sms.py. If I generated an sms.pyo from that module, Bad Magic Number error was the result. When I changed the name to smst.py, the error went away. I checked back and forth to see if sms.py somehow interfered with any other module with the same name but I could not find any name collision. Even though the source of this problem remained a mistery for me, I recommend trying a module name change.