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
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():
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')
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')
Now all you need to do is place your clearscreen()
function wherever you require in your script, and voila!
Top comments (0)