[Tutor] resetting the python interpreter through manipulating globals()

Yi Qiang yqiang at gmail.com
Thu Feb 8 08:18:33 CET 2007

I have a program that talks to a python interpreter through pexpect  
(don't bother asking why ;).  What I would like to do is occasionally  
"reset" the interpreter to the state it would be in if it had just  
been launched.  I assumed I could simply clear out the globals()  
dictionary, minus '__builtins__' and some other important stuff, and  
recreate the globals.  But even a simple attempt has failed quite badly:

def reset_interpreter():
     r"""This method will reset a python interpreters globals  
dictionary with
         the one provided as the input parameter.

     # This will just try to delete all non important keys in globals
     for k in globals().keys():
         print k
         if k == '__builtins__':
                 del globals()[k]
                 del locals()[k]
     print globals()

This does not seem to work at all, any suggestions?


More information about the Tutor mailing list