Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ast
- from collections import defaultdict
- from pprint import pprint
- def main():
- with open("test2.py", "r") as source:
- tree = ast.parse(source.read())
- analyzer = Analyzer()
- analyzer.visit(tree)
- analyzer.report()
- class Analyzer(ast.NodeVisitor):
- def __init__(self):
- self.stats = defaultdict(list)
- # sample
- def visit_Import(self, node):
- for alias in node.names:
- self.stats["import"].append(alias.name)
- self.generic_visit(node)
- # sample
- def visit_ImportFrom(self, node):
- for alias in node.names:
- self.stats["from"].append(alias.name)
- self.generic_visit(node)
- def visit_FunctionDef(self, node):
- self.stats["def"].append(node.name)
- # if you comment line below, AST won't inspect
- # "inside" of function definitions
- print(dir(node))
- self.generic_visit(node)
- def visit_Call(self, node):
- # value sometimes is an Attribute (e.g. `glob.glob()`), but
- # sometimes is a Name (e.g. `print()`)
- if isinstance(node.func, ast.Attribute):
- self.stats["calls"].append(
- "%s.%s" % (node.func.value.id, node.func.attr)
- )
- elif isinstance(node.func, ast.Name):
- self.stats["calls"].append(
- node.func.id
- )
- self.generic_visit(node)
- def report(self):
- pprint(self.stats)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement