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.

rss
Comments
Thanks for this! This is very useful. I'm justing using curses here to get the number of columns, as you described above. Before, I was trying to use the command "resize" and parsing the output of that, but resize wasn't available to me on all the servers I needed to run my python code on.