I am taking input from user in python code. and as per user’s provided input I want to clear previous outputs in terminal.
so is there any function? So I can put it in my code.
I searched on internet but it showing me Shortcut keys from keyboard but I want to clear terminal with help of code.(not want to type terminal )
2
Answers
The commands will be slightly different depending on if you’re running Python in Windows or Linux/Mac (or a Unix like terminal while in Windows)
cls
.clear
.except either
cls
orclear
.To call the appropriate command from within a script, you need to import the
os
module and callos.system(cmd)
. This will return a value of 0 for success, so if you are testing it in the terminal directly you may see an extra 0 get displayed on the screen if you don’t put the return value into a variable.Here’s some code to call the correct function based on your os. os.name will return ‘nt’ for Windows or ‘posix’ for Mac/Linux
Calling the clear() function in your script should clear the terminal as needed.
You can clear the terminal with:
…or…
…which is probably more efficient than os.system(…)
The string is actually 2 CSI sequences. The first moves the cursor to the screen origin (1, 1). The second sequence is the clear screen directive