Executing previous stack frame
jeff at jmcneil.net
Thu Jan 22 20:47:05 CET 2009
On Jan 22, 9:49 am, sturlamolden <sturlamol... at yahoo.no> wrote:
> frame = sys._getframe().f_back is the previous stack frame. Is there
> any way to execute (with exec or eval) frame.f_code beginning from
> frame.f_lasti or frame.f_lineno?
> I am trying to spawn a thread that is initialized with the code and
> state of the previous stack frame.
What are you trying to accomplish? While it's possible to do, I can't
believe it's going to be very safe. Note that I'd never even consider
doing anything like this for anything of real consequence. That said,
it was kind of fun to figure out just for academic purposes...
back = sys._getframe().f_back
code_object = back.f_code
# Skip CALL_FUNCTION & POP_TOP, otherwise we create
# a loop.
code = code_object.co_code[back.f_lasti+4:]
c = types.CodeType(code_object.co_argcount,
code_object.co_stacksize, code_object.co_flags, code,
exec c in globals()
# Anything below here will run in both threads.
More information about the Python-list