Generate .pyc from Python AST?

后端 未结 2 398
情深已故
情深已故 2021-02-05 17:09

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 t

2条回答
  •  既然无缘
    2021-02-05 17:36

    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"'), '', '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)
    

提交回复
热议问题