abw333 abw333 - 26 days ago 6
Python Question

clear terminal (and history!) in Python

This is almost a duplicate of clear terminal in python, but not quite.

That question reads: Does any standard "comes with batteries" method exist to clear the terminal screen from a python script, or do I have to go curses (the libraries, not the words) ?

All of the responses there result in what happens when you enter

clear
on your terminal - everything on your screen disappears except for an empty command line at the very top. But, if you'd like, you can scroll back up to see what you were doing earlier.

I'm looking for a way to do this, but to not allow the user to scroll back up. It's the equivalent of what
command+K
does on macOS.

The application is a multiplayer card game, and I don't want a player to be able to scroll back up to see another player's hand.

Answer

You could use subprocess.call() from the standard library subprocess module to send the reset command to the terminal which will reinitialize the terminal and in effect do something similar to clear but also clear the scrollback history.

import subprocess
subprocess.call('reset')

Alternatively, I have learned from this answer, that you can use the command tput reset instead, which will clear the terminal instantly, whereas with reset alone you will experience a slight delay. This can also be called with subprocess.call() as follows:

subprocess.call(['tput', 'reset'])

For more info on the reset command, do:

$ man reset

For more info on the subprocess module, see the documentation.

I have tested both of these on Ubuntu, but hopefully the will work on OSX/macOS as well. If not, perhaps you can use subprocess combined with this solution, but I am unable to test that.