Possible to execute Python bytecode from a script?

Is there a way to run the data from a pyc file directly?

The compiled code object can be saved using marshal

import marshal
bytes = marshal.dumps(eggs)

the bytes can be converted back to a code object

eggs = marshal.loads(bytes)
exec(eggs)

A pyc file is a marshaled code object with a header

For Python3, the header is 16 bytes which need to be skipped, the remaining data can be read via marshal.loads.


See Ned Batchelder's blog post:

At the simple level, a .pyc file is a binary file containing only three things:

  • A four-byte magic number,
  • A four-byte modification timestamp, and
  • A marshalled code object.

Note, the link references Python2, but its almost the same in Python3, the pyc header size is just 16 instead of 8 bytes.


Assuming the platform of the compiled .pyc is correct, you can just import it. So with a file bar.pyc in the python path, the following works even if bar.py does not exist:

import bar
bar.call_function()