Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate .pyc from Python AST?

How would I generate a .pyc file from a Python AST such that I could import the file from Python?

I've used compile to create a code object, then written the co_code attribute to a file, but when I try to import the file from Python, I get an ImportError: Bad magic number in output.pyc.

like image 279
exupero Avatar asked Dec 25 '11 01:12

exupero


People also ask

When .PYC file is created?

When a Python source file (module) is imported during an execution for the first time, the appropriate . pyc file is created automatically. If the same module is imported again, then the already created . pyc file is used.

What is ast function in Python?

The ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like. An abstract syntax tree can be generated by passing ast.


Video Answer


2 Answers

The solution can be adapted from the py_compile module:

import marshal
import py_compile
import time
import ast

codeobject = compile(ast.parse('print "Hello World"'), '<string>', 'exec')

with open('output.pyc', 'wb') as fc:
    fc.write('\0\0\0\0')
    py_compile.wr_long(fc, long(time.time()))
    marshal.dump(codeobject, fc)
    fc.flush()
    fc.seek(0, 0)
    fc.write(py_compile.MAGIC)

like image 87
exupero Avatar answered Sep 21 '22 13:09

exupero


The compile standard function provides this function for both Python 2.x and Python 3.x. However, you will find that the AST representation between 2.x and 3.x is quite different, so be prepared for that.

like image 44
Greg Hewgill Avatar answered Sep 21 '22 13:09

Greg Hewgill