Anton M
Anton M

Reputation: 91

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

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.

Upvotes: 8

Views: 91190

Answers (5)

XxJames07-
XxJames07-

Reputation: 1826

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()

Upvotes: 1

erfan karimian
erfan karimian

Reputation: 29

Code to clear console output in Python for Linux:

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

Upvotes: 2

Specter Paul
Specter Paul

Reputation: 9

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

Upvotes: 0

devil in the detail
devil in the detail

Reputation: 3275

Adding following in jupyter worked for me:

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

Upvotes: 20

Barry Scott
Barry Scott

Reputation: 819

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()

Upvotes: 9

Related Questions