Source

astoptimizer / demo.py

Full commit
#!/usr/bin/env python
import dis
import sys
from astoptimizer import Config, parse_ast, optimize_ast, compile_ast
from astoptimizer.compatibility import ast

def main():
    if len(sys.argv) < 2:
        print("usage: %s code ..." % sys.argv[0])
        print("example: %s '1+1'" % sys.argv[0])
        sys.exit(1)
    code = '\n'.join(sys.argv[1:])

    config = Config('platform', 'pythonenv')
    print("Config features: %s" % ', '.join(sorted(config.features)))
    print("")

    tree = parse_ast(code)
    print("Original AST:")
    print(ast.dump(tree))
    print("")

    print("Original bytecode:")
    code = compile(code, "<string>", "exec")
    dis.dis(code)
    print("")

    tree = optimize_ast(tree, config)
    print("Optimised AST:")
    print(ast.dump(tree))
    print("")

    if sys.version_info >= (2,6):
        code = compile_ast(tree)
        print("Optimized bytecode:")
        dis.dis(code)
        print("")

        print("Exec:")
        exec(code)
    else:
        print("** Python 2.5 does not support compilation of AST to bytecode **")

if __name__ == "__main__":
    main()