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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#!/usr/bin/env python import subprocess command = ['tput', 'cols'] def get_terminal_width(): try: width = int(subprocess.check_output(command)) except OSError as e: print("Invalid Command '{0}': exit status ({1})".format( command[0], e.errno)) except subprocess.CalledProcessError as e: print("Command '{0}' returned non-zero exit status: ({1})".format( command, e.returncode)) else: return width def main(): width = get_terminal_width() if width: print(width) if __name__ == "__main__": main() |
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
There is 1 comment on this post
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).