Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
spy on variable in python
# https://stackoverflow.com/a/34620310/1733117
import sys
import dis
import random
watchme = 123
def foo():
global watchme
watchme = 122
def wait_for_changes():
curr_val = watchme
def tracefn(frame, event, arg):
global watchme
global changed_frame
if event == 'call':
frame.f_trace_opcodes = True
if watchme != curr_val:
changed_frame = frame
if event == 'opcode':
opcode = frame.f_code.co_code[frame.f_lasti]
opname = dis.opname[opcode]
print(f"XXX value changed to {watchme} in frame {frame} by opcode {opname}")
watchme = curr_val
return tracefn
sys.settrace(tracefn)
for i in range(100):
exec(f"""
def foo_{i}():
global watchme
watchme = {i}
""")
wait_for_changes()
def random_call():
n = random.randint(0, 99)
exec(f"foo_{n}()")
random_call()
random_call()
random_call()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment