栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python ast NodeTransformer Transformer代码转换 代码插桩 新增node节点 编译生成新函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python ast NodeTransformer Transformer代码转换 代码插桩 新增node节点 编译生成新函数

python ast NodeTransformer 代码插桩
import ast, astor, inspect

# 测试函数
def test_func(a,b):
    d = a + 2
    f = b + 5
    o = d + f
    return o

# 代码转换pass
class dump_trans(ast.NodeTransformer):
    def visit_Assign(self, node):
        dump_code = "print({})".format(node.targets[0].id)
        dump_node = ast.parse(dump_code).body[0]
        return node, dump_node

# 获取原函数ast
tast = ast.parse(inspect.getsource(test_func)).body[0]

# 进行代码插入
dt = dump_trans()
ntast = dt.visit(tast)

# ast 转换成 源代码 str
new_code = astor.to_source(ntast)
print(new_code)
'''
def test_func(a,b):
    d = a + 2
    print(d)
    f = b + 5
    print(f)
    o = d + f
    print(o)
    return o
'''

# 执行新代码 编译 生成 新函数对象
local={}
exec(new_code, {}, local)

print(local)

new_f = local["test_func"]


# 执行新函数
new_f(6, 9.0)
# 会有打印信息



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/916033.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号