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 example:

>>> bytecode_compile([ ('LOAD_CONST', 2), ('STORE_FAST', 'a'), ('LOAD_FAST', 'a'), ('RETURN_VALUE',)]) 'd\x01\x00}\x00\x00|\x00\x00S' 
+10
python bytecode
source share
2 answers

I don’t think there is a Python assembler "bytecode assembly", but it may not be so difficult to build it yourself. In the python source code in Python-XYZ / Include / opcode.h, all bytecodes for opcodes are listed with the arguments that they accept.

+3
source share

I wrote about this in detail here, so I will not repeat it, but I will give some brief comments.

This is definitely doable, but I wonder how useful it will be. The link goes on how to run and write such things.

The byte code can be changed both in terms of the operation code and the names of the operation code or semantics of operation codes between versions. In fact, in Python 3.6 and later, bytecode becomes a code word.

However, if you decide to go this route, xdis recently added a list2bytecode() function to do this.

If you prefer to work in a text file, since most assembler code is written, I wrote xasm for this. Here is an example assembly in a format that you can use:

 # Python bytecode 3.6 (3379) # Method Name: five # Filename: /tmp/five.pl # Argument count: 0 # Kw-only arguments: 0 # Number of locals: 0 # Stack size: 1 # Flags: 0x00000043 (NOFREE | NEWLOCALS | OPTIMIZED) # First Line: 1 # Constants: # 0: None # 1: 5 2: LOAD_CONST (5) RETURN_VALUE # Method Name: <module> # Filename: /tmp/five.pl # Argument count: 0 # Kw-only arguments: 0 # Number of locals: 0 # Stack size: 2 # Flags: 0x00000040 (NOFREE) # First Line: 1 # Constants: # 0: <code object five at 0x0000> # 1: 'five' # 2: None # Names: # 0: five # 1: print 1: LOAD_CONST 0 (<code object five at 0x0000>) LOAD_CONST ('five') MAKE_FUNCTION 0 STORE_NAME (five) 3: LOAD_NAME (print) LOAD_NAME (five) CALL_FUNCTION 0 CALL_FUNCTION 1 POP_TOP LOAD_CONST (None) RETURN_VALUE 
+3
source share

All Articles