What\'s the \"Bad magic number\" ImportError in python, and how do I fix it?
The only thing I can find online suggests this is caused by compiling a .py -> .pyc file
The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.
Python puts a similar marker into its pyc
files when it creates them.
Then the python interpreter makes sure this number is correct when loading it.
Anything that damages this magic number will cause your problem. This includes editing the pyc
file or trying to run a pyc
from a different version of python (usually later) than your interpreter.
If they are your pyc
files, just delete them and let the interpreter re-compile the py
files. On UNIX type systems, that could be something as simple as:
rm *.pyc
or:
find . -name '*.pyc' -delete
If they are not yours, you'll have to either get the py
files for re-compilation, or an interpreter that can run the pyc
files with that particular magic value.
One thing that might be causing the intermittent nature. The pyc
that's causing the problem may only be imported under certain conditions. It's highly unlikely it would import sometimes. You should check the actual full stack trace when the import fails?
As an aside, the first word of all my 2.5.1(r251:54863)
pyc
files is 62131
, 2.6.1(r261:67517)
is 62161
. The list of all magic numbers can be found in Python/import.c
, reproduced here for completeness (current as at the time the answer was posted, it may have changed since then):
1.5: 20121
1.5.1: 20121
1.5.2: 20121
1.6: 50428
2.0: 50823
2.0.1: 50823
2.1: 60202
2.1.1: 60202
2.1.2: 60202
2.2: 60717
2.3a0: 62011
2.3a0: 62021
2.3a0: 62011
2.4a0: 62041
2.4a3: 62051
2.4b1: 62061
2.5a0: 62071
2.5a0: 62081
2.5a0: 62091
2.5a0: 62092
2.5b3: 62101
2.5b3: 62111
2.5c1: 62121
2.5c2: 62131
2.6a0: 62151
2.6a1: 62161
2.7a0: 62171
This can also happen if you have the wrong python27.dll file (in case of Windows), to solve this just re-install (or extract) python with the exact corresponding dll version. I had a similar experience.
In my case, I've git clone
a lib which had an interpreter of
#!/usr/bin/env python
While python
was leading to Python2.7
even though my main code was running with python3.6 ... it still created a *.pyc
file for 2.7
version ...
I can say that this error probably is a result of a mix between 2.7 & 3+ versions, this is why cleanup ( in any way you can think of that you're using ) - will help here ...