我正在使用python来解析python代码.说我正在解析的代码是:
def foo():
global x, y
x = 1
y = 2
print x + y
Run Code Online (Sandbox Code Playgroud)
我想在代码中找到全局x和y的所有用法.我有一个提前使用的全局变量列表,因此不需要从全局变量行中提取x和y.所以问题是:给定一些已知的全局变量列表在某些python代码中使用,例如['x','y']在这种情况下,如何解析代码以查找这些全局变量的用法?
您可以使用ast来解析python代码
from __future__ import print_function
import ast
src = """def foo():
global x, y
x = y = 1
y = 2
print x + y"""
s = ast.parse(src)
gvars = set()
for i in ast.walk(s):
# get globals
if isinstance(i,ast.Global):
for j in ast.walk(i):
gvars = gvars.union(i.names)
#get id-s of globals
for (field_type,value) in ast.iter_fields(i):
if field_type == "id" and value in gvars:
print(value , "at line", i.lineno)
Run Code Online (Sandbox Code Playgroud)
这个输出
x at line 3
y at line 3
y at line 4
x at line 5
y at line 5
Run Code Online (Sandbox Code Playgroud)
对于范围而言,这仍然无法正常工作,但仍会在源中找到某些id的所有实例.
范围解析问题的示例:
global x,y
def foo():
x = y = 1
global y
x = y = 2
# only global y is 2
def bar():
#here x and y are not global
x = y = 3
foo()
bar()
print(x,y) # runtime error. x undefined
Run Code Online (Sandbox Code Playgroud)
我们希望我们的代码只产生
-y in bar func
- x,y at end
但是它会打印出所有出现的x,y