Created
January 4, 2021 18:32
-
-
Save dnozay/d0dc461583caa723d014f71e654a6e0f to your computer and use it in GitHub Desktop.
spy on variable in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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