'Possible to execute Python bytecode from a script?

Say I have a running CPython session,

Is there a way to run the data (bytes) from a pyc file directly? (without having the data on-disk necessarily, and without having to write a temporary pyc file)

Example script to show a simple use-case:

if foo:
    # Intentionally ambiguous, since the data source
    # is a detail and answers shouldn't depend this detail.
    data = read_data_from_somewhere()
else:
    data = open("bar.pyc", 'rb').read()

assert(type(data) is bytes)

code = bytes_to_code(data)

# call a method from the loaded code
code.call_function()

Exact use isn't important, but generating code dynamically and copying over a network to execute is one use-case (for the purpose of thinking about this question).


Here are some example use-cases, which made me curious to know how this can be done:

  • Checking Python scripts for malicious code.
    If a single command can access a larger body of code hidden in binary data, what would that command look like?
  • Dynamically generate code and cache it for re-use (not necessarily on disk, could use a data-base for example).
  • Ability to send pre-compiled byte-code to a process, control an application which embeds Python for eg.


Solution 1:[1]

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()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 poke