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
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
with open(a) as f:
    tree = ast.parse(
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
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?
Due to the reasons discussed here we will be moving to on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 11 guests