Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear/overwrite standard output in Python

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.

like image 945
Anton M Avatar asked May 06 '16 11:05

Anton M


4 Answers

Adding following in jupyter worked for me:

from IPython.display import clear_output
clear_output(wait=True)
like image 106
devil in the detail Avatar answered Oct 01 '22 05:10

devil in the detail


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()
like image 45
Barry Scott Avatar answered Oct 01 '22 06:10

Barry Scott


Code to clear console output in Python for Linux:

def clear():
    os.system('clear')
like image 41
erfan karimian Avatar answered Oct 01 '22 05:10

erfan karimian


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

like image 25
Specter Paul Avatar answered Oct 01 '22 06:10

Specter Paul