alinsoar
alinsoar

Reputation: 15793

Clear the environment of the evalutor

Can I clear python environment, such that to bring the evaluator at the same state machine as after startup ?

I wish I would not restart the evalutor.

Upvotes: 1

Views: 121

Answers (2)

Aya
Aya

Reputation: 41950

You can't truly reset the state of the Python interpreter just with Python code, although you could do it with a custom C program which embeds the Python interpreter.

However, for your particular case, it would probably suffice to run each of your "problems" in a sub-interpreter, with something like this...

import sys
import code

def reset():
    raise SystemExit(123)

sys.modules['__builtin__'].reset = reset

banner = None

while 1:
    try:
        code.interact(banner=banner, local={})
        break
    except SystemExit as e:
        if e.code == 123:
            banner = 'Resetting...'
            continue
        raise

...then when you run that script, you can use it like this...

Python 2.7.4 (default, Apr 19 2013, 18:28:01)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> dir()
['__builtins__']
>>> a = 1
>>> dir()
['__builtins__', 'a']
>>> reset()
Resetting...
>>> dir()
['__builtins__']

Upvotes: 4

jh314
jh314

Reputation: 27792

How about this:

>>>globals().clear()

Upvotes: 1

Related Questions