我有一个简单的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
有没有办法做到这一点
每个目标要么是具有
id
属性的对象,要么是目标序列当然,这不会处理像
a, (b, c) = [3, [4,5]]
这样更复杂的可能赋值,但我把它作为一个练习,编写一个遍历树的递归函数,在找到目标名称时打印它们。(您可能还需要调整代码以处理a[3] = 5
或a.b = 10
之类的事情。)相关问题 更多 >
编程相关推荐