如何解析python中循环语句的开始和结束

Kau*_*hik 3 python parsing

我的目标是在 python 中找到循环语句开始和结束的行号。

示例场景

#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 
Run Code Online (Sandbox Code Playgroud)

当前解析器代码

#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              
Run Code Online (Sandbox Code Playgroud)

我想实现上述输出。我使用 AST 来解析给定的文件并确定循环的发生。通过 AST 解析,我能够找到循环开始的行号,但循环结束的行号尚未确定。有什么办法可以解析整个循环语句并确定其开始和结束行号吗?

tor*_*rek 6

一个While节点在它的node.body列表中有它的语句。while循环的最后一行是列表的最后一个元素。我不知道你为什么要减去一个(除非你的文件a有一个你想假装不存在的评论):

$ cat a.py
a = 0 
while a < 5:
    print a
    a += 1
for i in (1, 2, 3): 
    pass
$ cat ast_ex.py
import ast

with open('a.py') as f:
    tree = ast.parse(f.read())

for node in ast.walk(tree):
    if isinstance(node, (ast.For, ast.While)):
        print 'node:', node, 'at line:', node.lineno
        print 'body of loop ends at:', node.body[-1].lineno
$ python ast_ex.py 
node: <_ast.While object at 0x8017a8e50> at line: 2
body of loop ends at: 4
node: <_ast.For object at 0x8017ac0d0> at line: 5
body of loop ends at: 6
Run Code Online (Sandbox Code Playgroud)

循环中的第一行是 in body[0](这可能与循环中body[-1]只有一个语句一样)。