using windows 10 and pyhton3.5 i have tested many codes and nothing helped me more than this:
First define a simple function, this funtion will print 50 newlines;(the number 50 will depend on how many lines you can see on your screen, so you can change this number)
def cls(): print ("\n" * 50)
then just call it as many times as you want or need
This function works in any OS (Unix, Linux, macOS, and Windows) Python 2 and Python 3
import platform # For getting the operating system name
import subprocess # For executing a shell command
def clear_screen():
"""
Clears the terminal screen.
"""
# Clear command as function of OS
command = "cls" if platform.system().lower()=="windows" else "clear"
# Action
return subprocess.call(command) == 0
In windows the command is cls, in unix-like systems the command is clear. platform.system() returns the platform name. Ex. 'Darwin' for macOS. subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l'])
I am using a class that just uses one of the above methods behind the scenes... I noticed it works on Windows and Linux... I like using it though because it's easier to type clear() instead of system('clear') or os.system('clear')
pip3 install clear-screen
from clear_screen import clear
Here's how to make your very own cls or clear command that will work without explicitly calling any function!
We'll take advantage of the fact that the python console calls repr() to display objects on screen. This is especially useful if you have your own customized python shell (with the -i option for example) and you have a pre-loading script for it. This is what you need:
import os
class ScreenCleaner:
def __repr__(self):
os.system('cls') # This actually clears the screen
return '' # Because that's what repr() likes
cls = ScreenCleaner()
Use clear instead of cls if you're on linux (in both the os command and the variable name)!
Now if you just write cls or clear in the console - it will clear it! Not even cls() or clear() - just the raw variable. This is because python will call repr(cls) to print it out, which will in turn trigger our __repr__ function.
Let's test it out:
>>> df;sag
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'df' is not defined
>>> sglknas
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sglknas' is not defined
>>> lksnldn
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'lksnldn' is not defined
>>> cls
And the screen is clear!
To clarify - the code above needs to either be imported in the console like this