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

This is the place for queries that don't fit in any of the other categories.

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

Postby karthiksridhar » Tue Jul 30, 2013 10:37 am

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

Example scenario

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

Desired output:
Code: Select all
Start of a loop Line2
End of a loop   Line4

Current parser code
Code: Select all
#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 gives 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 ?
Last edited by Yoriz on Tue Jul 30, 2013 4:53 pm, edited 1 time in total.
Reason: Added code tags
karthiksridhar
 
Posts: 1
Joined: Tue Jul 30, 2013 10:34 am

Re: How to parse the starting and ending of a loop statement

Postby Yoriz » Tue Jul 30, 2013 5:21 pm

I've never used ast but it looks like you might need to use node.col_offset to get the indentation at the line that has a loop,
then continue stepping through lines untill the indentation returns back to the same level to get the end of the loop.

How to automatically get the indent level from code?
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 831
Joined: Fri Feb 08, 2013 1:35 am
Location: UK


Return to General Coding Help

Who is online

Users browsing this forum: snippsat and 4 guests