On Jan 22, 9:49 am, sturlamolden <[email protected]> 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.
>
> S.M.
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...
import sys
import types
import threading
def do_something_we_should_not_do():
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:]
def tmain():
c = types.CodeType(code_object.co_argcount,
code_object.co_nlocals,
code_object.co_stacksize, code_object.co_flags, code,
code_object.co_consts, code_object.co_names,
code_object.co_varnames,
code_object.co_filename, code_object.co_name,
code_object.co_firstlineno,
code_object.co_lnotab)
exec c in globals()
threading.Thread(target=tmain).start()
do_something_we_should_not_do()
# Anything below here will run in both threads.
print threading.current_thread()
Thanks,
Jeff
mcjeff.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list