tyrion

inspect_stack.py

Dec 2nd, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. import ctypes, inspect, random
  2.  
  3. def id2obj(i):
  4.     """convert CPython `id` back to object ref, by temporary pointer swap"""
  5.     tmp = None,
  6.     try:
  7.         ctypes.cast(id(tmp), ctypes.POINTER(ctypes.c_ulong))[3] = i
  8.         return tmp[0]
  9.     finally:
  10.         ctypes.cast(id(tmp), ctypes.POINTER(ctypes.c_ulong))[3] = id(None)
  11.  
  12. def introspect():
  13.     """pointer on top of value stack is id of the object about to be returned
  14.    FIXME adjust for sum(vars, locals) in introspected function
  15.    """
  16.     fr = inspect.stack()[1][0]
  17.     print "caught", id2obj(ctypes.cast(id(fr), ctypes.POINTER(ctypes.c_ulong))[47])
  18.  
  19. def value():
  20.     tmp = "TEST"
  21.     print "return", tmp
  22.     return tmp
  23.  
  24. def foo():
  25.     try:
  26.         return value()
  27.     finally:
  28.         introspect()
  29.  
  30. if __name__ == "__main__":
  31.     foo()
Advertisement
Add Comment
Please, Sign In to add comment