I can't find a simple command that does this. If there's no command that does this I'm going to spam python.org until they finally agree to put this in the next version of python.

Recommended Answers

All 12 Replies

Python.org supposedly loves spam anyway, so long as you include some eggs.

I was hoping for a more insightful answer :(

Sigh.

No, python doesn't have clear screen.

there's not even some way to trick the computer into clearing the screen of text?

I suggest

>>> print("\n" * 40)

Or even better

>>> def clear():
...      print("\n"*40)
>>> clear()

Last one:

>>> def clear():
...      import sys
...      for i in range(40):
...          print(sys.ps1)

The last one doesn't work, says the attribute ps1 doesn't exist. But that is what I was planning to do at first, but then that leaves a big side bar. Oh well, I guess I'll just have to use the print thing.

Clearing the display screen in console mode depends on the Operating System, that and the limited usefulness is why many multiplatform computer languages do not include it.

Here is a Python version using module os ...

import os
# works on windows nt (also xp and vista) or linux
os.system(['clear','cls'][os.name == 'nt'])
commented: nothing for idle ? +4
commented: Very helpful and clear. +1

That works perfect! Now the problem is really solved.

import os
# works on windows nt (also xp and vista) or linux
os.system(['<strong class="highlight">clear</strong>','cls'][os.name == 'nt'])

Can anyone kindly explain the background of how this bit of code works?

import os
# works on windows nt (also xp and vista) or linux
os.system(['<strong class="highlight">clear</strong>','cls'][os.name == 'nt'])

Can anyone kindly explain the background of how this bit of code works?

I suppose you pasted this from a web page. It doesn't work. The following works

import os
# works on windows nt (also xp and vista) or linux
os.system(['clear','cls'][os.name == 'nt'])

if the system is nt, then os.name=='nt' returns True, which is converted to the integer 1 and ['clear','cls'][1] is 'cls', which is passed to os.system. On another system, 'clear' is passed.
This is old style coding. Nowadays, one writes

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

(By the way, using os.system is outdated too)

Well, I don't use that. I usually def them as function. Thanks for the post though anyway.

import os
# works on windows nt (also xp and vista) or linux
os.system(['clear','cls'][os.name == 'nt'])

If [os.name == 'nt'] is True then this becomes effectively 1. So it picks item at index 1 from the list which is the Windows command 'cls'. If it's False, it becomes 0 and the item at index 0 (zero) is used, which is the Linux command 'clear'.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.