2

Long-time lurker, first time asker.

Is there a way to automatically clear the terminal in Python 3 regardless of what platform the app is being used in?

I've come across the following (from this answer) which utilises ANSI escape codes:

import sys
sys.stderr.write("\x1b[2J\x1b[H")

But for it to work cross-platform it requires the colorama module which appears to only work on python 2.7.

For context I'm learning Python by building a game of battleships, but after each guess I want to be able to clear the screen and re-print the board.

Any help is appreciated!

Cheers

Sean Coley
  • 147
  • 1
  • 10

2 Answers2

0

I know of this method

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

I'm not sure if it works with other platforms, but it's working in windows python 3.x

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

That might work for linux and OS X, but I can't test.

El-Chief
  • 383
  • 3
  • 15
  • I think this has already been dealt with here: https://stackoverflow.com/questions/2084508/clear-terminal-in-python The simple answer is that there is not perfect, cross-platform way to do this other than output a heap of newline characters. However, there are techniques that will work on most common platforms. – Kevin Boone Sep 02 '17 at 14:39
  • Yeah that's the answer I linked in my original post. The answer given could be made cross-platform by use of the colorama module (which converted ANSI escapes for windows), but it only works on python 2.7. This is probably the best option for now. – Sean Coley Sep 03 '17 at 01:24
  • When I try this in OS X it gives me the error 'TERM environment variable not set'. Ideas? – Sean Coley Sep 03 '17 at 01:27
  • Check also my answer, @KevinBoone – Pitto Oct 25 '18 at 15:22
0

I use a single snippet for all the platforms:

import subprocess
clear = lambda: subprocess.call('cls' if os.name=='nt' else 'clear')
clear()

Same idea but with a spoon of syntactic sugar:

import subprocess   
clear = lambda: subprocess.call('cls||clear', shell=True)
clear()
Pitto
  • 8,229
  • 3
  • 42
  • 51