如何解析python代码以识别全局变量使用? [英] How to parse python code to identify global variable uses?

查看:134
本文介绍了如何解析python代码以识别全局变量使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python解析python代码.说我要解析的代码是:

I'm using python to parse python code. Say the code I'm parsing is:

def foo():
    global x, y
    x = 1
    y = 2
    print x + y

我想在代码中找到全局变量x和y的所有用法.我提前列出了要使用的全局变量,因此无需从全局变量行中提取x和y.所以问题是:给定在某些python代码中使用的全局变量的已知列表,例如['x','y']在这种情况下,如何解析代码以查找这些全局变量的用法?

I want to find all uses of the globals x and y in the code. I have a list of the globals being used ahead of time, so there's no need to extract x and y from the globals line. So the question is: given a known list of globals being used in some python code, e.g. ['x', 'y'] in this case, how do I parse the code to find uses of those globals?

推荐答案

您可以使用ast来解析python代码

You can use ast to parse python code

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)

此输出

x at line 3
y at line 3
y at line 4
x at line 5
y at line 5

就范围而言,这仍然无法正常工作,但仍会在源代码中找到某个ID的所有实例.

This still doesn’t work correctly with respect on scope, but still finds all instances of some id in source.

范围分析问题的示例:

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 

我们希望我们的代码仅产生
-y in bar func
-x,y结尾
但它会打印所有出现的x,y

we would want our code to yield only
- y in bar func
- x,y at end
but it prints all occurrence's of x,y

这篇关于如何解析python代码以识别全局变量使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆