Clear/overwrite standard output in Python

65,466

Solution 1

I see a syntax error from your code, you are missing the ":".

clear = lambda : os.system('cls')

However avoid lambda and define a function for clear because it is easier to read.

def clear():
    os.system( 'cls' )

then you can clear the window with:

clear()

Solution 2

Adding following in jupyter worked for me:

from IPython.display import clear_output
clear_output(wait=True)

Solution 3

Code to clear console output in Python for Linux:

def clear():
    os.system('clear')

Solution 4

First, install IPython using the Python package installer pip:

pip install IPython

In your script write the following

form IPython.display import clear_output

I guess by now it should be working

Share:
65,466
Admin
Author by

Admin

Updated on November 30, 2021

Comments

  • Admin
    Admin over 2 years

    Hi I'm trying to make a tic-tac-toe game in Python and I've run into a problem.

    1

    As you can see on the picture it rewrites the playing board after input, what I want it to do is to clear the output and then rewrite the board. So instead of just printing new boards all the time it only clears the current board and rewrites it. I've searched on "clear output" etc, but found only these snippets:

    import os
    
    clear = lambda: os.system('cls')
    

    or

    import os
    
    def clear():
        os.system('cls')
    

    However, it doesn't work for me. It only returns this symbol: 2

    I am currently writing my code in PyCharm and just to make it clear, I want to keep it in PyCharm.

  • Admin
    Admin about 8 years
    When I use clear it only returns i.gyazo.com/d928370f9a4ebaf1ba3d7e07142d7489.png
  • Barry Scott
    Barry Scott about 8 years
    Where are you running you code? Given you are using CLS that implies you are windows and running python in a CMD.exe window. If you are not try that are see if that solves the problem.
  • Admin
    Admin about 8 years
    I'm running my code in pycharm that's probably why 'cls' does not work but that's the only way I found when I tried to google it.