[Tutor] How to "refresh" the interactive prompt?

Steven D'Aprano steve at pearwood.info
Sun Oct 2 10:47:17 CEST 2011

Richard D. Moores wrote:
> Python 3.2.2, Win 7
> When using the Python 3 interactive prompt, is there a way to quickly
> "refresh" the prompt? By "refresh" I mean get a new interactive prompt
> with nothing imported and all things like  a = "qwerty",   n = 123,
> etc. no longer in effect. Not sure what the wording should be for
> that. "imports cancelled and variables deleted"?

That would be "start a fresh interpreter session".

And the easiest way to start a fresh interpreter session is, indeed, to 
exit the current session and start a fresh one, just as you describe.

> I know I can do that by entering a Ctrl+z, followed by entering
> "python". But could print() be used to do the same thing? I can get a
> beep with print("\a"), or clear the screen with   import os;
> print(os.system("CLS"),chr(13)," ",chr(13)), but how to print a ^Z?

Printing a ^Z is easy, you just have to know what character code ^Z 
corresponds to. That's chr(26) or 1A in hexadecimal, so this works:

 >>> print('\x1A')

But as you can see, that just prints a character.

You need to get Ctrl-Z into the *input* stream, not the *output* stream, 
to exit the interpreter. If you are doing it manually, the easiest way 
is just to type Ctrl-Z. If doing it programmatically, use either of these:

raise SystemExit

There is no easy way to reset the current interpreter session to "as 
new". I suppose you could try something like this:

sys.modules[:] = []

but that won't necessarily reset everything to a fresh state.


More information about the Tutor mailing list