1

This code returns the size of the terminal window.

def gettermsize():
    s = struct.pack("HHHH", 0, 0, 0, 0)
    a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
    return (a[0], a[1])

What is it actually doing?

Kevin Burke
  • 61,194
  • 76
  • 188
  • 305

1 Answers1

2

In general ioctrl calls will allow the operator to query &/or set various characteristics of a physical or logical device - which values are available and how to get at them are specific to the device and device type. In this case the standard output console, (a handle to which is provided by sys.stdout.fileno()), is being queried for a terminal device, (termios), window size (TIOCGWINSZ), and it needs a struct of 4 16 bit unsigned values to work in (s), it returns as 4 signed values the first two of which are used presumably as the height and width. The reason that you need to pack/unpack values is that this is actually a call to C code directly.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73