[Tutor] Clear screen questions

boB Stepp robertvstepp at gmail.com
Mon May 6 02:17:18 CEST 2013


I have been playing around with my own version of a guess the number
game that I wrote before looking at how the kids' book (which I am
reviewing for my kids) did it. For some reason my children are
fascinated by this game and keep asking me for improvements. The
latest one was to implement an automatic clearing of the screen if the
user wishes to play again. So I got my handy-dandy pocket reference
out and added to the existing code at the appropriate places:

import os
...
os.system('cls')

The kids were pleased, but I wasn't. Yes, this works on Windows/DOS,
but nowhere else. So how to make this OS-independent? Googling has not
yielded a truly cross-platform solution. Currently, I have temporized
with:

os.system('cls' if os.name=='nt' else 'clear')

which I think will work for Windows/UNIX. I am not certain it would
work with DOS, since NT came after DOS, but who has DOS these days?

So my main question is there a truly clean, cross-platform solution to
the clear screen dilemma? If my online searching is accurate, then the
answer appears to be no, unless one wants to print many blank lines.

A second question is that one person had as the answer to use:

os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )

I don't understand this syntax. The writer said that if one
understands what this is doing, then the method is more generally
useful. Would someone explain how this works? And hopefully it will
become apparent to me how this is more generally useful?

Finally, a minor, secondary question: I was curious how my clear
screen code would run in the IDLE Python shell window, since I know
there is currently no way to clear its screen (other than the blank
line approach). Of course it did not clear the screen, but it did do
something unexpected that I would like to understand. Upon hitting the
clear screen code the active window switched from the Python shell
window to the Python edit window. Why is this so?

As always thanks!
boB


More information about the Tutor mailing list