get the terminal's size

Cameron Simpson cs at cskk.id.au
Mon Jan 14 17:43:42 EST 2019


On 14Jan2019 17:16, Alex Ternaute <alex at lussinan.invalid> wrote:
>>> Looking on the internet for a hint, I see that python3 has an
>>> os.get_terminal_size().
>> Use that then.
>
>Up to now I wanted to keep compatibility with a big bunch of code in
>Python2 that I do no maintain by myself.
>
>Well, I saw that get_terminal_size() follows the windows resizings.
>Whenever I consider forking to Python3, this would be my 1st step.
>
>>> Please, is there something similar for python2 ?
>> I suspect there is some solution in the curses module...
>
>I did  dir(curse) but I could not see if something goes this way.

My cs.tty module (on PyPI) has a ttysize function:

  https://pypi.org/project/cs.tty/

which just parses the output of the stty command.

Personally I resist using the environment variables; they're (a) not 
exports by default because they're "live" and (b) then don't track 
changes if they are exported and (c) rely on the shell providing them. I 
just don't trust them.

If you don't want the cs.tty module, the ttysize code is just this:

    WinSize = namedtuple('WinSize', 'rows columns')

    def ttysize(fd):
      ''' Return a (rows, columns) tuple for the specified file descriptor.

          If the window size cannot be determined, None will be returned
          for either or both of rows and columns.

          This function relies on the UNIX `stty` command.
      '''
      if not isinstance(fd, int):
        fd = fd.fileno()
      P = Popen(['stty', '-a'], stdin=fd, stdout=PIPE, universal_newlines=True)
      stty = P.stdout.read()
      xit = P.wait()
      if xit != 0:
        return None
      m = re.compile(r' rows (\d+); columns (\d+)').search(stty)
      if m:
        rows, columns = int(m.group(1)), int(m.group(2))
      else:
        m = re.compile(r' (\d+) rows; (\d+) columns').search(stty)
        if m:
          rows, columns = int(m.group(1)), int(m.group(2))
        else:
          rows, columns = None, None
      return WinSize(rows, columns)

Hope this helps.

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list