Measuring the Terminal

I found this site with a lot of neat terminal tricks, like making text bold, changing colors, and adding a progress bar. I use the recipe for measuring the width of the terminal a good bit, so I’ll reproduce that here.

This uses some Python modules I’ve never heard of, and I’m not entirely sure what it’s doing, but it works.

import fcntl, struct, termios
COLS = struct.unpack( 'hh', fcntl.ioctl( sys.stdout, termios.TIOCYGWINSZ, '1234' ) )[1]

Here, COLS is an integer representing the width of the terminal in characters.