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
from somefile import cls
Or pre load directly with something like:
python -i my_pre_loaded_classes.py