How to clean python interpreter's environment?

Peter Hansen peter at engcorp.com
Fri Aug 20 15:38:47 EDT 2004


Reinhold Birkenfeld wrote:

>>Rafal Kleger-Rudomin wrote:
>>
>>>I'm looking for a command to reset interpreter's environment i.e. unload 
>>>all modules, delete variables etc.
> 
> What about something like this:
> 
> def clear(keep=("__builtins__", "clear")):
>     keeps = {}
>     for name, value in globals().iteritems():
>         if name in keep: keeps[name] = value
>     globals().clear()
>     for name, value in keeps.iteritems():
>         globals()[name] = value

Well, that only removes all the references from the
globals of the current module.  Is that all that's
wanted?

Note that threads that are already running will not be
removed, nothing in sys.modules will be removed, and
there are doubtless a few other things in the interpreter
that aren't quite so easy to get at.

-Peter



More information about the Python-list mailing list