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

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

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

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

当前回答

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

其他回答

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

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

#!/usr/bin/env python

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

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

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

如果您手动以.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.

如果你有错误的python27.dll文件(在Windows的情况下),也会发生这种情况,要解决这个问题,只需重新安装(或提取)python与精确对应的dll版本。我也有过类似的经历。