Originally posted on my blog.
When working with the python interactive shell, you may end up having a cluttered screen. For Windows and Linux users, one can run
clear to clear their screens. But this doesn't seem to cut it while working in the python shell. Here are a few quick tips to achieve this in python.
We need to get into python shell first 😆. To do this, type
python in your terminal or if you want to access the Django DB shell,
python manage.py shell will suffice.
The simplest method is using
ctrl+l for Linux/OS X terminals.
Another handy way is by using the os module that ships with the standard python library. This module provides a portable way of using operating system dependent functionality.
from os import system clear = lambda: system('clear')
We are utilising python's lambda functions to achieve this functionality. By calling on the underlying os
clear function for UNIX based system and assigning that to our newly created clear function.
This way if we want to clear the screen we can call the function like so
for windows systems, the following would work just as well.
from os import system cls = lambda: system('cls')
and call the function in the python shell by running
Note that you don't have to declare the function as clear or cls. You can name them whatever you want, as long as you use that name when calling them.
import os os.getcwd()
In my case, this returned
This should work similar to
cd .. returning
similar to the
For more information on the os module, check out the documentation
Thanks for reading and feel free to contact me if you have any questions on twitter.