DEV Community

loading...

Clearing terminal in any OS

importhuman profile image Ujjwal Goyal ・1 min read

Compatibility of a program across different operating systems is very important, and going through a project codebase, I found one operation which might be of use. I didn't expect to learn cross-platform operations this early in my learning process, so I found it really cool, and figured I'd share.

You might need to clear the terminal screen for certain scripts. That's where the os module comes in handy. It is a part of the Python standard library, so you do not need to install it separately. We'll need the module objects system and name, so:

from os import system, name
Enter fullscreen mode Exit fullscreen mode

Since you want to clear the terminal, it's likely that you'll be doing it multiple times, so it's best to define a function.

def clearscreen():
Enter fullscreen mode Exit fullscreen mode

Next, we want to check the operating system. Windows operating systems have the name value "nt", while Unix-based operating systems have the name value "posix". Both of them take different functions to clear the screen, which can be done as follows:

if name == "nt":
    system('cls')
else:
    system('clear')
Enter fullscreen mode Exit fullscreen mode

Thus, the if statement runs for Windows, and the else statement runs for Linux/MacOS.
Our complete code becomes:

from os import system, name
def clearscreen():
if name == "nt":
    system('cls')
else:
    system('clear')
Enter fullscreen mode Exit fullscreen mode

Now all you need to do is place your clearscreen() function wherever you require in your script, and voila!

Discussion (0)

pic
Editor guide