Terminal manipulation in Python
A seemingly oft-asked question is how to clear the console/terminal/screen in Python. This is really a subset of a larger question: how does one control and query the terminal from Python?
The basic steps are:
- Initialise curses
import curses curses.setupterm()
- Query a capability
# Escape sequence used to clear the terminal clear = curses.tigetstr('clear') # Number of colours terminal supports colours = curses.tigetnum('colors') # Number of columns columns = curses.tigetnum('cols') # Number of lines lines = curses.tigetnum('lines')
- Use a capability
# Clear the screen import sys sys.stdout.write(clear)
PS. Ideally, you'd check to see if the capability queries return None.
