What's the bad magic number error? What's the bad magic number error? python python

What's the bad magic number error?

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


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:   201211.5.1: 201211.5.2: 201211.6:   504282.0:   508232.0.1: 508232.1:   602022.1.1: 602022.1.2: 602022.2:   607172.3a0: 620112.3a0: 620212.3a0: 620112.4a0: 620412.4a3: 620512.4b1: 620612.5a0: 620712.5a0: 620812.5a0: 620912.5a0: 620922.5b3: 621012.5b3: 621112.5c1: 621212.5c2: 621312.6a0: 621512.6a1: 621612.7a0: 62171

Deleting all .pyc files will fix "Bad Magic Number" error.

find . -name "*.pyc" -delete

Loading a python3 generated *.pyc file with python2 also causes this error.