~andrew-monkeysailor/python-snippets/ast-snippets

« back to all changes in this revision

Viewing changes to AST/ASTcount.py

  • Committer: user
  • Date: 2010-04-05 00:03:54 UTC
  • Revision ID: user@user-pc-20100405000354-tvob1tvyu3d1jck9
ASTĀ snippet

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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>]
 
5
# [SNIPPET_DOCS:]
 
6
# [SNIPPET_LICENSE: GPL]
 
7
 
 
8
import ast, _ast
 
9
 
 
10
class ASTcount():
 
11
    """ Spit out a list of imports from a python file"""
 
12
    def __init__(self, txt):
 
13
        self.source = ast.parse(txt)
 
14
 
 
15
    def imports(self):
 
16
        # Get the names of import statements
 
17
        # and return as a list
 
18
        output = []
 
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))
 
24
 
 
25
if __name__ == "__main__":
 
26
    
 
27
    # read in a python file
 
28
    f = open("parser.py","r")
 
29
    x = "".join(f.readlines())
 
30
    f.close()
 
31
 
 
32
    # create instance and print imports and variable names
 
33
    counter = ASTcount(x)
 
34
    print counter.imports()