doekman
doekman

Reputation: 19278

How to determine the number of columns in a UNIX shell

I want to determine the number of columns in a window for my sh/bash-script. I'm now using tput cols, but I found out that on some platforms (Synology) the tput library is not available.

I know there's a C library for this, but a binary is not an option.

Python3 is an option, but I haven't found anything in the help files...

An alternative to tput cols, if at all possible...

Upvotes: 3

Views: 394

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295472

The Right Way: Python Standard Library

Python 3 supports shutil.get_terminal_size(), which itself falls back to os.get_terminal_size() should Python not have been invoked from a shell which exported COLUMNS and LINES (as bash does, when running in interactive mode with a TTY attached).


Less Right: Asking A Shell From Python

If you want to get this information through a shell, some shells (including bash) will expose it in interactive mode. The following (while lacking adequate error handling) showcases this:

#!/usr/bin/env python3
import subprocess, sys
p = subprocess.Popen(['bash', '-i'],
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE,
                     stderr=sys.stderr)
out = p.communicate(b'''printf '%s\n' "$COLUMNS" "$LINES"''')[0]
cols, lines = out.split(b'\n')[:2]
print("Cols: {}; lines: {}".format(int(cols), int(lines)))

Upvotes: 4

Related Questions