In Python, you can clear the output in various ways depending on the context in which you want to clear it. Here are some common methods:
Clearing the Terminal/Console Output:
If you’re working in a terminal or console and want to clear the output, you can use platform-specific commands. In most cases, you can use the following:
- For Windows: Use the
clscommand to clear the console.
import os os.system('cls')
- For Unix/Linux/Mac: Use the
clearcommand to clear the terminal.
import os os.system('clear')
os.system function allows you to run system commands, so use it with caution, especially if you’re taking input from untrusted sources.
Clearing Jupyter Notebook Output:
If you’re working in a Jupyter Notebook, you can clear the output of a specific cell or all cells. To clear the output of a specific cell, you can go to the “Cell” menu and select “Current Outputs” -> “Clear.” To clear the output of all cells, you can select “Edit” -> “Clear All Outputs.”
Clearing Output in Python Code:
If you want to clear the output of a code cell within a Jupyter Notebook or an IDE like VSCode or PyCharm, you can use the following methods:
- Use the
IPythonlibrary if you are working in a Jupyter Notebook:
from IPython.display import clear_output clear_output()
- If you are using other Python IDEs or environments, you can use the
osmodule as mentioned in method 1 to clear the terminal or console output.
Clearing the output is often done for presentation purposes or to provide a clean slate for displaying new information without the clutter of old output.
Python clear output example
To clear the output in a Windows console or terminal, you can use the
os.system function to execute the
cls command. Here’s an example:
import os # Display some output print("This is some output.") input("Press Enter to clear the screen...") # Clear the screen (Windows-specific) os.system('cls')
In this example, we first import the
os module and then display some output using
input to wait for the user to press Enter before clearing the screen.
os.system('cls') line executes the
cls command, which clears the terminal or console screen in a Windows environment.
When you run this code, it will display “This is some output.” on the screen, wait for you to press Enter, and then clear the screen. This is a simple way to clear the output in a Windows console.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.