get the terminal's size

Wildman best_lay at yahoo.com
Wed Jan 16 20:59:49 EST 2019


On Mon, 14 Jan 2019 11:57:33 +0000, Alex Ternaute wrote:

> Hi there,
> 
> I want to know the number of columns of the terminal where python2 writes 
> it's outputs.
> 
> In a terminal, I type
> $ echo $COLUMNS
> 100
> 
> But in Python, os.getenv("COLUMNS") gets nothing.
> It gets nothing as well if I try to read the output of "echo $COLUMNS" 
> from a subprocess.
> 
> I feel that I'm missing something but what ?
> 
> Looking on the internet for a hint, I see that python3 has an  
> os.get_terminal_size(). 
> Please, is there something similar for python2 ?
> 
> Cheers

I have used this Python2 code with success in Linux...

#!/usr/bin/env python

import fcntl
import os
import struct
import termios

tty = os.open(os.ctermid(), os.O_RDONLY)
ts = struct.unpack("hh", fcntl.ioctl(tty, termios.TIOCGWINSZ, "1234"))
os.close(tty)
print str(ts[1]) + "x" + str(ts[0])

-- 
<Wildman> GNU/Linux user #557453
"There are only 10 types of people in the world...
those who understand Binary and those who don't."
  -Spike



More information about the Python-list mailing list