1
# [SNIPPET_NAME: Reading AST]
2
# [SNIPPET_CATEGORIES: AST]
3
# [SNIPPET_DESCRIPTION: Scans the AST to find import statements]
4
# [SNIPPET_AUTHOR: Andrew Lewis <andrew@monkeysailor.co.uk>]
6
# [SNIPPET_LICENSE: GPL]
11
""" Spit out a list of imports from a python file"""
12
def __init__(self, txt):
13
self.source = ast.parse(txt)
16
# Get the names of import statements
17
# and return as a list
19
for each in self.source.body:
20
if type(each)== _ast.Import:
21
for modules in each.names:
22
output.append(modules.name)
23
return list(set(output))
25
if __name__ == "__main__":
27
# read in a python file
28
f = open("parser.py","r")
29
x = "".join(f.readlines())
32
# create instance and print imports and variable names
34
print counter.imports()