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

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

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

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

当前回答

将pyc文件保存到windows计算机上。使用十六进制编辑器打开这个pyc文件。我使用免费软件“HexEdit”。现在读取前两个字节的十六进制值。在我的例子中,这些是03 f3。

打开calc并将其显示模式转换为编程模式(XP中的科学模式),以查看十六进制和十进制转换。从单选按钮中选择“Hex”。首先输入第二个字节的值,然后是第一个字节,即f303现在点击“Dec”(十进制)单选按钮。显示的值是1,对应于python版本的魔法数字。

所以,考虑到之前回复中提供的表格

1.5 => 20121 => 4E99,因此文件的第一个字节为99,第二个字节为4e 1.6 => 50428 => C4FC,因此文件的第一个字节为fc,第二个字节为c4

其他回答

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

将pyc文件保存到windows计算机上。使用十六进制编辑器打开这个pyc文件。我使用免费软件“HexEdit”。现在读取前两个字节的十六进制值。在我的例子中,这些是03 f3。

打开calc并将其显示模式转换为编程模式(XP中的科学模式),以查看十六进制和十进制转换。从单选按钮中选择“Hex”。首先输入第二个字节的值,然后是第一个字节,即f303现在点击“Dec”(十进制)单选按钮。显示的值是1,对应于python版本的魔法数字。

所以,考虑到之前回复中提供的表格

1.5 => 20121 => 4E99,因此文件的第一个字节为99,第二个字节为4e 1.6 => 50428 => C4FC,因此文件的第一个字节为fc,第二个字节为c4

所以我有同样的错误:ImportError坏魔术数字。这是windows 10上的

这个错误是因为我安装了mysql-connector

所以我不得不:

pip uninstall mysql-comnector
pip uninstall mysql-connector-python
pip install mysql-connector-python