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

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

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

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

当前回答

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.

其他回答

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

#!/usr/bin/env python

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

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

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

这也可能是由于目录中缺少__init__.py文件。比如,如果你在Django中创建了一个新目录,用于将单元测试分离为多个文件,并将它们放在一个目录中,那么你还必须在新创建的测试目录中的所有其他文件旁边创建__init__.py文件。否则它会给出如下错误:

Traceback (most recent call last):
  File "C:\Users\USERNAME\AppData\Local\Programs\Python\Python35\Lib\unittest\loader.py",line 153, in loadTestsFromName
    module = __import__(module_name)
ImportError: bad magic number in 'APPNAME.tests': b'\x03\xf3\r\n'

不要删除它们!!直到 ..........

在你的git, svn或复制文件夹中找到一个有效的版本。

删除它们,然后恢复所有的.pyc。

那是我的工作。

删除所有.pyc文件将修复“坏魔术数字”错误。

find . -name "*.pyc" -delete

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.