ast_visualizer_1.py 970 B

1234567891011121314151617181920212223242526272829
  1. def main(args):
  2. parser = optparse.OptionParser(usage="astvisualizer.py [options] [string]")
  3. parser.add_option("-f", "--file", action="store",
  4. help="Read a code snippet from the specified file")
  5. parser.add_option("-l", "--label", action="store",
  6. help="The label for the visualization")
  7. options, args = parser.parse_args(args)
  8. if options.file:
  9. with open(options.file) as instream:
  10. code = instream.read()
  11. label = options.file
  12. elif len(args) == 2:
  13. code = args[1]
  14. label = "<code read from command line parameter>"
  15. else:
  16. print("Expecting Python code on stdin...")
  17. code = sys.stdin.read()
  18. label = "<code read from stdin>"
  19. if options.label:
  20. label = options.label
  21. code_ast = ast.parse(code)
  22. transformed_ast = transform_ast(code_ast)
  23. renderer = GraphRenderer()
  24. renderer.render(transformed_ast, label=label)