如何解析 python 代码只获取没有缩进的变量?

How to parse python code and only get variables with no indentation?

我正在尝试提取代码中没有缩进的所有变量,这是一个简单的示例:

import ast
import astunparse
class AnalysisNodeVisitor(ast.NodeVisitor):
    def __init__(self, nodename):
        super().__init__()
        self.nodename=nodename
        self.setVariables={}
    def visit_Assign(self,node):
        print(self.nodename,astunparse.unparse(node.targets))
        #print(ast.dump(node))

        
Analyzer=AnalysisNodeVisitor("example1")
tree=ast.parse('''\
a = 10

for i in range(10):
    b=x+i

if(x==10):
    c=36

d=20
''')
Analyzer.visit(tree)

output:

example1 a

example1 b

example1 c

example1 d

此示例打印出所有 4 个变量(a、b、c 和 d),我想知道是否有办法让它只打印赋值 a、d,因为它们的赋值前没有缩进?

我试图转储节点,看看是否有什么东西可以用来过滤掉变量,但我找不到任何东西(例如它只输出这个:'Assign(targets=[Name(id= 'a', ctx=Store())], value=Num(n=10))').

我想如果你只看 tree.body,你可以找到你所有的顶级赋值语句。

运行 这段代码:

import ast
import astunparse

tree=ast.parse('''\
a = 10

for i in range(10):
    b=x+i

if(x==10):
    c=36

d=20
''')

for thing in tree.body:
    if isinstance(thing, ast.Assign):
        print(astunparse.unparse(thing.targets))

生产:


a


d