abw333 abw333 - 1 year ago 254
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

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
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 Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download