Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Python bytecode from list of opcodes and arguments?

Is there an easy way to create Python bytecode from a list of 2-tuples with opcodes and their arguments?

For instance:

>>> bytecode_compile([
        ('LOAD_CONST', 2),
        ('STORE_FAST', 'a'),
        ('LOAD_FAST', 'a'),
        ('RETURN_VALUE',)])
'd\x01\x00}\x00\x00|\x00\x00S'
like image 470
exupero Avatar asked Jan 23 '12 13:01

exupero


People also ask

How do you generate bytecode in Python?

Byte Code is automatically created in the same directory as . py file, when a module of python is imported for the first time, or when the source is more recent than the current compiled file. Next time, when the program is run, python interpretator use this file to skip the compilation step.

What is Co_code Python?

In Python, every element of the language (functions, methods, classes, ...) is defined and stored in an object. The co_code is one of the fields attached to the class used to represent a function or a method.

What is disassembled bytecode?

The disassembler converts the byte-compiled code into human-readable form. The byte-code interpreter is implemented as a simple stack machine. It pushes values onto a stack of its own, then pops them off to use them in calculations whose results are themselves pushed back on the stack.

Can Python be compiled to machine code?

Python doesn't convert its code into machine code, something that hardware can understand. It actually converts it into something called byte code. So within python, compilation happens, but it's just not into a machine language.


1 Answers

I don't think a Python "bytecode assembly" assembler exists, but it might not be that hard to build one yourself. In the python source code in Python-X.Y.Z/Include/opcode.h, all of the bytecodes for the opcodes are listed with what arguments they take.

like image 131
GuillaumeDufay Avatar answered Oct 16 '22 12:10

GuillaumeDufay