Python Sys Trace
for Fun and for Profit
Batteries Included
sys.settrace(cb)
docs.python.org/2/library/sys.html#sys.settrace
Events?
- function call
- line executed
- function return
- exception
Demo
Trace Lines/Calls/Returns
Frame Object
- Represents an execution frame
- Same as the frame in tracebacks
- Contains:
- the previous frame (f_back)
- the line number (f_lineno)
- reference to the code object (f_code)
Code Object
- CPython implementation detail
- represents a chunk of executable code
- contains metadata about the code
- file/function name
- arguments
- etc
What can I use it for?
- Debugging
- Coverage
- Profiling
Practical Use
for a certain value of "practical"
"Reverse" Coverage
def add(x, y):
z = x + y
return z
def subtract(x, y):
z = x - y
return z
def test_add():
assert 1 == worker.add(1, 0)
def test_add___negative():
assert 0 == worker.add(-1, 1)
def test_subtract():
assert 0 == worker.subtract(0, 0)
"Reverse" Coverage
def add(x, y):
z = x + y # test_add, test_add_negative
return z # test_add, test_add_negative
def subtract(x, y):
z = x - y # test_subtract
return z # test_subtract
nostrils
nosetests --with-nostrils --nostrils-whitelist=xyz
Demo
Summary
- sys.settrace(cb)
- def cb(frame, event, arg): ...
- lots of interesting stuff in frame/code obj
- batteries make Python awesome!
- Caveat: CPython-dependent
Resources
Official Python doc
https://docs.python.org/2/library/sys.html#sys.settrace
Python-Aware Python (Ned Batchelder PyCON2011)
http://pyvideo.org/video/447/pycon-2011--python-aware-python
nostrils nose plugin
Python Sys Tracefor Fun and for Profit
By Kevin Jing Qiu
Python Sys Tracefor Fun and for Profit
- 881