如何获取 python 文件中所有“if”、“else”和“elif”位置的行号

Alo*_*loy 0 python abstract-syntax-tree

示例:假设我们有一个包含以下代码片段的 .py 文件。我们如何读取并提取 if-elif-else 的位置

If fisrtconditon:#line 1
    If sub-condition:#line2
       print(line no 3)
elif secnd_condn:#line 4
     Xyz..#line5
     Xyz..#line6
elif third condition:line7
     ...line 8
else:#line 9
    Some content #line10***
Run Code Online (Sandbox Code Playgroud)

输出:

[1,4,7,9]
Run Code Online (Sandbox Code Playgroud)

Rob*_*aut 5

您可以使用该ast模块。

import ast

with open('file.py') as f:
    tree = ast.parse(f.read())  # parse the file

for node in ast.walk(tree):  # walk the tree
    if isinstance(node, ast.If):  # if the node is an If (or an If-else)
        print('If at line', node.lineno)  # print the line number
        if node.orelse:  # if the node has an else
            if isinstance(node.orelse[0], ast.If):  # if the else is an If
                print('Elif at line', node.orelse[0].lineno)  # print the line number
            else:
                print('Else at line', node.orelse[0].lineno)  # print the line number

Run Code Online (Sandbox Code Playgroud)

ast 是标准库的一部分,因此无需安装任何东西。它代表抽象语法树,它是代码结构的表示。您可以在ast 模块文档中找到更多信息。