![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4
![]() |
Hacking the Python compiler
I've been looking into generating Python bytecode from a Python program and this is what I've come up with:
def write_pyc(code, filename):
"Write code to a PYC file"
file = open(filename, 'wb')
# PYC header specifying version and timestamp
file.write(imp.get_magic())
file.write(struct.pack('<l', time.time()))
marshal.dump(code, file)
file.close()
def compile_module(parse_tree, filename):
"Compile a raw AST module"
parse_tree.filename = filename
return compiler.pycodegen.ModuleCodeGenerator(parse_tree).getCode()How do you create an AST? A good way to get a feel of Python ASTs is to get Python to generate them for you from existing files: print compiler.parseFile(py_filename) Here's an AST I constructed myself: module = ast.Module(
None,
ast.Stmt(
[ast.Printnl(
[ast.CallFunc(
ast.Name('pow'), [ast.Const(2), ast.Const(2)], None, None
)],
None
)]
)
)To compile this AST and write it to a file: filename = "four.pyc" write_pyc(compile_module(module, filename), filename) python four.pyc |
|
|
|
|
|
#2 |
|
Hobbyist Programmer
|
Python is interpreted, isn't it?
__________________
When will Jesus bring the porkchops? |
|
|
|
|
|
#3 | |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4
![]() |
Quote:
All this makes Python much faster than a purely interpreted language. |
|
|
|
|
|
|
#4 |
|
Troll
Join Date: Apr 2005
Location: Texas
Posts: 730
Rep Power: 4
![]() |
Pretty much like C# or Java.
__________________
MD5(sig) = bcef75433db02e9ad9bf81d6f7c5c270 |
|
|
|
|
|
#5 | |
|
Hobbyist Programmer
Join Date: Oct 2005
Posts: 134
Rep Power: 3
![]() |
Quote:
A couple days ago, I started building the compiler for my virtual machine project (so sick of AST's right now) and when it's all set up, I'm going to make a basic python front end (probably not a full front end right away but some basic features) and so I can test python vs. mine. |
|
|
|
|
|
|
#6 | |
|
Programmer
Join Date: Apr 2005
Posts: 73
Rep Power: 4
![]() |
Quote:
-T. |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|