Skip to content

Instantly share code, notes, and snippets.

@shiumachi
Created November 29, 2018 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shiumachi/4a618e609f3245ab834c9e089579177d to your computer and use it in GitHub Desktop.
Save shiumachi/4a618e609f3245ab834c9e089579177d to your computer and use it in GitHub Desktop.
# sample of ast module
# reference:
# http://docs.python.jp/2.7/library/ast.html
# http://stackoverflow.com/questions/1515357/simple-example-of-how-to-use-ast-nodevisitor
import ast
import sys
import logging
class SampleVisitor(ast.NodeVisitor):
def generic_visit(self, node):
print("type of node: {0}".format(type(node).__name__))
ast.NodeVisitor.generic_visit(self, node)
def visit_Load(self, node):
pass
def visit_Name(self, node):
print("Name: {0}".format(node.id))
def visit_Num(self, node):
print("Num: {0}".format(node.n))
if len(sys.argv) != 2:
logging.error("usage: ast_example.py [word]")
sys.exit(1)
expr = sys.argv[1]
print("expression: {0}".format(expr))
tree = ast.parse(expr)
sv = SampleVisitor()
sv.visit(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment