Python Snippet: Get Terminal Width

There is a wonderful command on UNIX systems to return the width of the current terminal. Enter  tput cols and see for yourself! Tput can actually provide a lot of different info by querying the terminfo database. Really all I’ve needed though is ‘cols’ for columns.

I was writing a Python CLI app, and wanted to format and print output in a nice table. To do that (without downloading a table printing module) I had to know how much space was available for printing. Can’t make a nice-looking set of data if every other line is being wrapped!

Here is a simple function that returns the width of whatever terminal is running the script. Subprocess is the most current built-in Python module for running system commands. It contains a selection of different functions each with many optional parameters, depending on the complexity of your needs. Using subprocess.check_output() is the way to go if you are looking to get back the output of a command. The  check_output() function has a whole slew of accepted arguments, but in this simple instance we need only one: a list containing command to run and the arguments to pass to it.

The first exception will be raised if the system returns an error when trying to execute the tput command. The second exception will be raised if the command (in our case tput) has a problem with the given argument ( cols). If nothing goes wrong, the output will be a nice whole number that you can use to determine exactly how many characters can be printed per line!

Have you ever needed to know the width of your terminal? If you have any questions please feel free to ask in the comments below!

Here’s a link to this code snippet on Github Gists: terminal_width.py

One thought on “Python Snippet: Get Terminal Width

  1. This was very helpful.
    I did move the command assignment into the function, as I think this makes sense, this way something else in the script will not overwrite the command and you can then cut/paste this elsewhere and have everything you need (except the import statement).

Leave a Reply