Pregunta

for example can I do something like this

pythonCode = "print 'hello world'"
pyc = generate_bytecode(pythonCode)

where pyc would contain the bytecode for pythonCode?

Edit: My goal is essentially to get exactly what would would be written to a .pyc in file into a variable. magic number, timestamp, hex version of code and all

¿Fue útil?

Solución 3

Use the compiler package:

The compiler package is a Python source to bytecode translator written in Python. It uses the built-in parser and standard parser module to generate a concrete syntax tree. This tree is used to generate an abstract syntax tree (AST) and then Python bytecode.

Otros consejos

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        

It's called compile:

>>> compile('print "Hi!"', 'abc', 'single')
<code object <module> at 0000000002555D30, file "abc", line 1>
>>> eval(compile('print "Hi!"', 'abc', 'single'))
Hi!
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top