Restart the interactive python shell like in IDLE

Terry Reedy tjreedy at udel.edu
Thu Jun 11 15:04:22 EDT 2009


Chris Rebert wrote:
> On Wed, Jun 10, 2009 at 12:01 PM, Matt Burson<msburson at gmail.com> wrote:
>> Is there a way to reproduce the behavior of IDLE's restart shell ability by
>> using a function? I thought there would be since you can exit python by
>> executing the simple quit() function I thought there would be an equally
>> simple function name something like restart(). I'd prefer something like
>> this as opposed to having to exit the shell and then start it up again to
>> refresh it.
> 
> I believe IDLE itself implements the "restart" capability by killing
> and re-launching its Python interpreter subprocess, so it's not like
> it's using some hidden capability of Python to accomplish this.
> Is doing Ctrl+D, up-arrow, Enter really that hard? It's even fewer
> keystrokes than "restart()"...

This will do part of what you want:

 >>> a=1
 >>> b=1
 >>> globals().clear()
 >>> a
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

That will not reset sys.modules, which is the only other thing I can 
imagine being worried about.

The main reason IDLE has a restart is so that when you run a file after 
editing, you can be sure the behavior you see is what you get when 
running the file without IDLE, with a fresh interpreter.  Another use of 
refresh is when creating example interactive sessions for doctest or 
book examples.  Again, one wants to make sure that the example does not 
depend on previous entries not included in the example.  For ordinary 
interactive exploration, refresh is seldom needed.

tjr




More information about the Python-list mailing list