Clear terminal in Python
What about escape sequences?
print(chr(27) + "[2J")
How do I clear the screen in Python 3?
It prints the menu again because you call main()
again instead of just stopping there. :-)
elif choice == "2":
os.system("cls")
main() # <--- this is the line that causes issues
Now for the clearing itself, os.system("cls")
works on Windows and os.system("clear")
works on Linux / OS X as answered here.
Also, your program currently tells the user if their choice is not supported but does not offer a second chance. You could have something like this:
def main():
...
while True:
choice = input("Please enter option 1 or 2")
if choice not in ("1", "2"):
print("that is not a valid option")
else:
break
if choice == "1":
...
elif choice == "2":
...
main()
Clear screen in shell
For macOS/OS X, you can use the subprocess module and call 'cls' from the shell:
import subprocess as sp
sp.call('cls', shell=True)
To prevent '0' from showing on top of the window, replace the 2nd line with:
tmp = sp.call('cls', shell=True)
For Linux, you must replace cls
command with clear
tmp = sp.call('clear', shell=True)
How to clear the interpreter console?
As you mentioned, you can do a system call:
For Windows:
>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()
For Linux it would be:
>>> import os
>>> clear = lambda: os.system('clear')
>>> clear()
Clearing the screen of IDLE interactive mode
cls
and clear
are commands which will clear a terminal (ie a DOS prompt, or terminal window). If you are using the shell within IDLE, which won't be affected by such things, a workaround might be to print a lot of empty lines with print("\n" * 100)
. See also this answer for more information.
Related Topics
Repeating Elements of a List N Times
Obtain Active Window Using Python
How to Input Integers Using Input in Python
Is Distributing Python Source Code in Docker Secure
List VS Tuple, When to Use Each
Using Logging in Multiple Modules
How Does Functools Partial Do What It Does
When to Use "While" or "For" in Python
How to Write Png Image to String with the Pil
Create a "With" Block on Several Context Managers
How to Transform an Xml File Using Xslt in Python
Differencebetween Class and Instance Variables
What Does a . in an Import Statement in Python Mean
How to Ignore Deprecation Warnings in Python