Skip to content

Instantly share code, notes, and snippets.

@plashchynski
Created March 17, 2025 14:08
Show Gist options
  • Save plashchynski/7e2819f69c659e16128b786c38b79ec5 to your computer and use it in GitHub Desktop.
Save plashchynski/7e2819f69c659e16128b786c38b79ec5 to your computer and use it in GitHub Desktop.
log all opcodes in Python in realtime
import sys
import gc
from dis import get_instructions
def local_trace(frame, event, arg):
"""
The 'local' trace function, called for *each* opcode (if f_trace_opcodes=True)
or line (if f_trace_lines=True).
"""
# Turn on opcode-level tracing for this frame
frame.f_trace_opcodes = True
if event == 'opcode':
offset = frame.f_lasti
instrs = get_instructions(frame.f_code)
for instr in instrs:
if instr.offset == offset:
print(instr, end='')
else:
sys.stderr.write(f"TRACE: event={event}, line={frame.f_lineno}, arg={arg}\n")
return local_trace
def global_trace(frame, event, arg):
"""
The 'global' trace function, called for *function calls* and returns.
Here we decide to attach our local tracer to every new frame.
"""
# Return the local trace function for the *new* frame
return local_trace
N=10000000
gc.disable()
def test():
for _ in range(N):
bytes.fromhex('')
# Enable tracing
# sys.settrace(global_trace)
test()
# sys.settrace(None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment