Passing 'exec'
as the mode
to compile()
will generate a code object from Python statements. Accessing the co_code
attribute of the code object will give you the raw bytecode. Note that this alone will be mostly useless without the other co_*
attributes though.
>>> c = compile('print a', '<string>', 'exec')
>>> dir(c)
['__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
>>> c.co_code
'e\x00\x00GHd\x00\x00S'
>>> c.co_names
('a',)
>>> c.co_consts
(None,)
>>> dis.dis(c)
1 0 LOAD_NAME 0 (a)
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE