简体   繁体   English

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

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

I'm trying to extract all variables in my code that have no indentation, here is a simple example:我正在尝试提取代码中没有缩进的所有变量,这是一个简单的示例:

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 : output

example1 a

example1 b

example1 c

example1 d

This example prints out all the 4 variables(a,b,c and d) and I'm wondering if there is a way to make it only print the assignments a,d since there is no indentation before their assignments?此示例打印出所有 4 个变量(a、b、c 和 d),我想知道是否有办法让它只打印分配 a、d,因为在分配之前没有缩进?

I tried to dump the nodes and see if there is something I can use to filter out the variables but I can't find anything (for example it just outputs this: 'Assign(targets=[Name(id='a', ctx=Store())], value=Num(n=10))').我试图转储节点,看看是否有什么东西可以用来过滤掉变量,但我找不到任何东西(例如它只输出这个:'Assign(targets=[Name(id='a', ctx =Store())],值=Num(n=10))')。

I think if you just look at tree.body , you can find all your top-level assignment statements.我想如果你只看一下tree.body ,你可以找到你所有的顶级赋值语句。

Running this code:运行此代码:

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))

Produces:产生:


a


d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM