I’ve been troubleshooting a problem that arose while running a pyc file: RuntimeError: Bad magic number in .pyc file

OK, so how do I find the magic number that is in the myfile.pyc and how do I find the magic number that was expected?

The magic number is the first two bytes of the file. I can get them using xxd:

robert@dante ~/MathScripts
$ xxd myfile.pyc | head -n 1
0000000: 330d 0d0a 33c7 925b 4c29 0000 e300 0000 3...3..[L)......

In other words, the magic number of the python36 version of myfile.pyc is 330d 0d0a.

The python27 version has a different magic number:

$ xxd ../MathScripts_py27/myfile.pyc | head -n
1 0000000: 03f3 0d0a 24d4 f75a 6300 0000 0000 0000 ....$..Zc.......

…namely 03f3 0d0a.

Having got the magic number of my byte-code file, how do I discover the magic number that my current python is expecting? The commands are different in python2 and 3.

In python2:

robert@dante ~
$ source activate py27
(py27)
robert@dante ~
$ python
Python 2.7.15 |Anaconda, Inc… <snip>
>>> import imp
>>> imp.get_magic().encode('hex')
'03f30d0a'

And in python3:

robert@dante ~
$ source activate py36
(py36)
robert@dante ~
$ python
Python 3.6.5 |Anaconda, Inc… <snip>
>>> import imp
>>> mp.get_magic().hex()
'330d0d0a'

There’s a full list of magic numbers here.