简体   繁体   English

在多个变量分配的情况下,如何从 python 代码中解析单个变量?

[英]How to parse individual variables from python code in case of multiple variables assignments?

I have this simple python code example that parses a python code and extracts the variables assigned in it:我有这个简单的 python 代码示例,它解析 python 代码并提取其中分配的变量:

import ast
import sys
import astunparse
import json

tree=ast.parse('''\
a = 10
b,c=5,6
[d,e]=7,8
(f,g)=9,10
h=20
''',mode="exec")

for thing in tree.body:
    if isinstance(thing, ast.Assign):
        print(astunparse.unparse(thing).split('=')[0].strip())

I also tried a similar method with a NodeVisitor:我还尝试了使用 NodeVisitor 的类似方法:

import ast
import sys
import astunparse
import json

tree=ast.parse('''\
a = 10
b,c=5,6
[d,e]=7,8
(f,g)=9,10
h=20
''',mode="exec")

class AnalysisNodeVisitor2(ast.NodeVisitor):
    def visit_Assign(self,node):
        print(astunparse.unparse(node.targets))
        
Analyzer=AnalysisNodeVisitor2()
Analyzer.visit(tree)

But both methods gave me this same results :但是这两种方法都给了我同样的结果

a
(b, c)
[d, e]
(f, g)
h

But the output I'm trying to get is individual variables like this:但我试图得到的 output 是这样的单个变量:

a
b
c
d
e
f
g
h

Is there a way to achieve this?有没有办法做到这一点?

Each target is either an object with an id attribute, or a sequence of targets.每个目标要么是一个带有id属性的 object,要么是一个目标序列。

for thing in tree.body:
    if isinstance(thing, ast.Assign):
        for t in thing.targets:
            try:
                print(t.id)
            except AttributeError:
                for x in t.elts:
                    print(x.id)

This, of course, doesn't handle more complicated possible assignments like a, (b, c) = [3, [4,5]] , but I leave it as an exercise to write a recursive function that walks the tree, printing target names as they are found.当然,这不能处理更复杂的可能分配,例如a, (b, c) = [3, [4,5]] ,但我将其作为练习编写一个遍历树的递归 function ,打印找到的目标名称。 (You may also need to adjust the code to handle things like a[3] = 5 or ab = 10 .) (您可能还需要调整代码以处理诸如a[3] = 5ab = 10之类的事情。)

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

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