Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

Python comes with a curses module, which basically lets you implement a GUI of sorts on a text screen. Players would not be able to scroll back to previous output, unless you intentionally implemented a scrolling text window. The terminal's scrollback feature doesn't do anything in a curses application, because nothing is actually scrolling off the screen - it's being overwritten instead.

Post a Comment for "Clear Terminal (and History!) In Python"