How to clear python console (i.e. Ctrl+L command l

2019-09-20 14:03发布

问题:

OS = Linux

[boris@E7440-DELL ~]$ uname -a
Linux E7440-DELL 3.17.4-200.fc20.x86_64 #1 SMP Fri Nov 21 23:26:41 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

From python console (Spyder 2.2.4, Python 2.7.5 64bits, Qt 4.8.5) it is seen as:

>>> import os
>>> print(os.name)
posix

I'm trying to find out a way to clear python console. Not just any solution is suitable, but it must be exactly same result as pressing Ctrl+L.

From other threads I have already tried several options:

>>> import os
>>> os.system('clear')
256

>>> import subprocess
>>> subprocess.call("clear", shell=True)
1

>>> print '\n'*1000

As you can see neither os.system('clear') nor subprocess.call("clear", shell=True) produce desired result. They just output a value (256 or 1 respectively). print '\n'*1000 is so far closest the desired outcome. However, there are two issues with it:

  1. the cursor is not at the top of the screen (as Ctrl+L does), but it stays at the bottom, so all new lines printed by my code are being scrolled upwards, which makes it impossible to read.
  2. the visual experience is highly dependent on the value, so in order to make it somewhat readable I have to use print '\n'*100000 instead

Does anyone know the right solution, the one that can really do Ctrl+L from the command line? (yes I am using linux, and I have no interest in windows solutions)

回答1:

You can try:

os.system('tput reset')

To hide the return value, use:

variable = os.system('tput reset')