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

2024-04-28 19:28:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的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())

我还尝试了一种与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)

但这两种方法都给了我同样的results

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

但我试图得到的输出是这样的单个变量:

a
b
c
d
e
f
g
h

有没有办法做到这一点


Tags: 代码importjsontreeparsemodesysast
1条回答
网友
1楼 · 发布于 2024-04-28 19:28:25

每个目标要么是具有id属性的对象,要么是目标序列

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)

当然,这不会处理像a, (b, c) = [3, [4,5]]这样更复杂的可能赋值,但我把它作为一个练习,编写一个遍历树的递归函数,在找到目标名称时打印它们。(您可能还需要调整代码以处理a[3] = 5a.b = 10之类的事情。)

相关问题 更多 >