Created
November 29, 2018 01:57
-
-
Save shiumachi/4a618e609f3245ab834c9e089579177d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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