How to parse the starting and ending of a loop statements in python

karthik sridhar karthiksridhar1990 at gmail.com
Tue Jul 30 06:40:10 EDT 2013


My objective is to find the line numbers of the start and the end of a loop statement in python.

Example scenario

#A.py
Line1: a=0                  
Line2: while a<5:           
Line3:    print a          
Line4:    a=a+1 

Desired output:
Start of a loop Line2 
End of a loop   Line4
 
Current parser code
#parser.py
with open(a) as f:
    tree = ast.parse(f.read())
taskline=[]
for node in ast.walk(tree):
    if isinstance(node, (ast.For)) or isinstance(node,(ast.While)):                        
        print node.lineno-1  <-- This give line number on for the start of a loop

I wanted to achieve the above output. I use AST to parse a given file and determine the occurrence of loops. With AST parsing i am able to find line number for the start of the loop but the line number for ending of the loop is yet to be determined. Is there any way i could parse an entire loop statement and determine its starting and ending line number ?



More information about the Python-list mailing list