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 and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.
The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:
Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
This can also be due to missing
__init__.py
file from the directory. Say if you create a new directory in django for seperating the unit tests into multiple files and place them in one directory then you also have to create the__init__.py
file beside all the other files in new created test directory. otherwise it can give error likeTraceback (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'
Take the pyc file to a windows machine. Use any Hex editor to open this pyc file. I used freeware 'HexEdit'. Now read hex value of first two bytes. In my case, these were 03 f3.
Open calc and convert its display mode to Programmer (Scientific in XP) to see Hex and Decimal conversion. Select "Hex" from Radio button. Enter values as second byte first and then the first byte i.e f303 Now click on "Dec" (Decimal) radio button. The value displayed is one which is correspond to the magic number aka version of python.
So, considering the table provided in earlier reply
Deleting all .pyc files will fix "Bad Magic Number" error.
This is much more efficent than above.
where
{directory-of-.pyc-files}
is the directory that contains the compiled python files.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.
I just faced the same issue with Fedora26 where many tools such as dnf were broken due to bad magic number for six. For an unknown reason i've got a file /usr/bin/six.pyc, with the unexpected magic number. Deleting this file fix the problem