Skip to content

Instantly share code, notes, and snippets.

@aisk
Created October 26, 2012 06:57
Show Gist options
  • Save aisk/3957320 to your computer and use it in GitHub Desktop.
Save aisk/3957320 to your computer and use it in GitHub Desktop.
generate a pyc file by hand. the bytecode's content is something like test.py content.
import marshal
import struct
import time
import imp
from opcode import opmap
def f(): return
code = type(f.__code__) # the code object type
code_list = (
struct.pack('B', opmap['LOAD_CONST']),
struct.pack('H', 0),
struct.pack('B', opmap['STORE_NAME']),
struct.pack('H', 0),
struct.pack('B', opmap['LOAD_CONST']),
struct.pack('H', 1),
struct.pack('B', opmap['STORE_NAME']),
struct.pack('H', 1),
struct.pack('B', opmap['LOAD_NAME']),
struct.pack('H', 0),
struct.pack('B', opmap['LOAD_NAME']),
struct.pack('H', 1),
struct.pack('B', opmap['BINARY_ADD']),
struct.pack('B', opmap['PRINT_ITEM']),
struct.pack('B', opmap['PRINT_NEWLINE']),
struct.pack('B', opmap['LOAD_CONST']),
struct.pack('H', 2),
struct.pack('B', opmap['RETURN_VALUE']),
)
code_string = ''.join(code_list)
code_args = (
0, # 'argcount' arguments count of the code object
0, # 'nlocals' ??
2, # 'stack_size' max size of the stack
64, # 'flags' ??
code_string, # 'codestring' the bytecode instructions
(1, 2, None), # 'constants' constants value for the code object
('a', 'b'), # 'names' used names in this code object
(), # 'varnames' variable names
'test.py', # 'filename' filename
'<module>', # 'name' name of the function/class/module
1, # 'firstlineno' the first line number of this code object
'\x06\x01\x06\x01', # 'lnotab' ??
(), # 'freevars' for closure
(), # 'cellvars': ??
)
co = code(*code_args)
bytecode_head = '\x03\xf3\r\n\x0f\x1c\x8aP' # magic number for 2.7
magic_string = imp.get_magic()
time_string = struct.pack('L', int(time.time()))
if __name__ == '__main__':
f = open('test.pyc', 'wb')
f.write(magic_string)
f.write(time_string)
marshal.dump(co, f)
print 'done!'
a = 1
b = 2
print a + b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment