Trying to clear/overwrite standard output using os.system('cls') in PyCharm does not work but prints a rectangle symbol

Question:

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.

Asked By: Anton M

||

Answers:

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()
Answered By: Barry Scott

Adding following in jupyter worked for me:

from IPython.display import clear_output
clear_output(wait=True)
Answered By: devil in the detail

Code to clear console output in Python for Linux:

def clear():
    os.system('clear')
Answered By: 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

Answered By: Specter Paul

It depends on the Operating System,
if you want to be sure you can do:

import os, platform
def clear():
   if platform.system() == 'Windows':
      os.system('cls')
   else:
      os.system('clear')

and call the function:

clear()

but if you want only for Windows OS (Windows 10/11/7/8/8.1 ecc..) is fine this:

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

and you call it as well:

clear()
Answered By: XxJames07-
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.