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

K

karthik sridhar

My objective is to find the line numbers of the start and the end of a loopstatement 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 ?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top