在python中捕获全局变量值的变化 [英] capture change of global variable value in python

查看:863
本文介绍了在python中捕获全局变量值的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python中检测或捕获全局变量的值变化

How do i detect or capture change of value of a global variable in python

variable = 10
print(variable)
variable = 20 
# Detect changes to the value using a signal to trigger a function

更新 AST文件-良好的简介 https://greentreesnakes.readthedocs.io/en/latest/

UPDATE AST docs - GOOD INTRO https://greentreesnakes.readthedocs.io/en/latest/

推荐答案

如何处理在存储到全局变量的每个语句之前添加打印语句的字节码.这是一个示例:

How about instrument the bytecode to add a print statement before each statement that stores to the global variable. Here is an example:

from bytecode import *

def instr_monitor_var(func, varname):
    print_bc = [Instr('LOAD_GLOBAL', 'print'), Instr('LOAD_GLOBAL', varname),
                Instr('CALL_FUNCTION', 1), Instr('POP_TOP')]

    bytecodes = Bytecode.from_code(func.__code__)
    for i in reversed(range(len(bytecodes))):
        if bytecodes[i].name=='STORE_GLOBAL' and bytecodes[i].arg==varname:
            bytecodes[i:i]=print_bc

    func.__code__=bytecodes.to_code()

def test():
    global a
    a = 1
instr_monitor_var(test, 'a')
test()

instr_monitor_var可以检测功能test,因此更改其全局变量a的值时,它将被打印出来.让我知道这个是否奏效.谢谢!

instr_monitor_var can instrument a function test so the global variable a will be printed out when its value is changed. Let me know if this works. Thanks!

这篇关于在python中捕获全局变量值的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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