Created
December 28, 2016 07:03
-
-
Save denis-ryzhkov/bd2d5285ade51d46d301668a574984a7 to your computer and use it in GitHub Desktop.
How sys.setprofile + greenlet.settrace can trace all calls/switches/returns
This file contains hidden or 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
#!/usr/bin/env python | |
import greenlet, time, sys | |
def sys_profiler(frame, event, arg): | |
if event == 'call' or event == 'return': | |
code = frame.f_code | |
print('g{} {} {}:{} {}()'.format(id(greenlet.getcurrent()), event, code.co_filename, code.co_firstlineno, code.co_name)) | |
sys.setprofile(sys_profiler) | |
def green_tracer(event, args): | |
if event == 'switch' or event == 'throw': | |
origin, target = args | |
print('g{} -> g{}'.format(id(origin), id(target))) | |
greenlet.settrace(green_tracer) | |
def alice_func(): | |
print('alice: 1') | |
bob = greenlet.greenlet(bob_func) | |
bob.switch() | |
print('alice: 2') | |
bob.switch() | |
def bob_func(): | |
print('bob: 1') | |
alice.switch() | |
print('bob: 2') | |
alice = greenlet.greenlet(alice_func) | |
alice.switch() | |
time.sleep(50) | |
""" | |
g140482924548976 -> g140482924548176 | |
g140482924548176 call ./test1.py:20 alice_func() | |
alice: 1 | |
g140482924548176 -> g140482924548336 | |
g140482924548336 call ./test1.py:27 bob_func() | |
bob: 1 | |
g140482924548336 -> g140482924548176 | |
alice: 2 | |
g140482924548176 -> g140482924548336 | |
bob: 2 | |
g140482924548336 return ./test1.py:27 bob_func() | |
g140482924548336 -> g140482924548176 | |
g140482924548176 return ./test1.py:20 alice_func() | |
g140482924548176 -> g140482924548976 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment