pythonterminalansi-escapeterminal-emulator

How can I “manually” get my terminal to return its (character) size?


Programs like resize ask the terminal about its size. And ultimately they will send some (ANSI) escape sequences to stdout and expect the terminal to react on those by itself returning some bytes.

The effect of the mechanism is visible with this interactive Python snippet:

>>> print('\x1b[21;t')

Gnome-terminal will insert visibly something related to the window title on stdin.

Which script snippet will provoke the terminal to write it’s size (in characters)? If the size is returned invisible, some simple transformation should be done to see something. Shell, Python, Perl, whatever language is fine. As this will be terminal specific, any common terminal emulator is fine (e.g. xterm, gnome-terminal, terminator, ...).

Clarification: I don’t care about programs which tell me the size. I know about TIOCGWINSZ, which does not work over serial lines. I want to see code which uses escape sequences, which actually works over serial lines.


Solution

  • The following program saves the current cursor position; moves the cursor to 999,999; queries the terminal for the current position; and restores the cursor position.

    Assuming that your terminal is smaller than 999x999, this effectively queries the size of the terminal.

    import sys
    print('\033[s\033[999;999H\033[6n\033[u')
    print(repr(next(sys.stdin)))
    

    Resources: