ActiveState Code

Recipe 440694: Determine size of console window on Windows


This recipe is Python implementation of few lines of C-code that get useful information about current working console on Windows. It may be useful for console application to proper formatting output. Recipe need ctypes package to be installed.

This is the second version of recipe. When use handle of stdout for determining size of console and connect output of program via pipe to another program (e.g. pager 'more') then you get default 80x25 size. In case of using handle of stderr for this purpose then pipe don't destroy actual size.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from ctypes import windll, create_string_buffer

# stdin handle is -10
# stdout handle is -11
# stderr handle is -12

h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)

if res:
    import struct
    (bufx, bufy, curx, cury, wattr,
     left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    sizex = right - left + 1
    sizey = bottom - top + 1
else:
    sizex, sizey = 80, 25 # can't determine actual size - return default values

print sizex, sizey

Discussion

Open new console window (on Windows 2K/XP press Start -> Run -> type 'cmd' and hit Enter). Change your current directory to one that contain this script. Resize console window with mouse and run this code. It will print actual console size as: columns rows.

Comments

  1. 1. At 9:51 a.m. on 12 dec 2006, Ernesto Savoretti said:

    Good stuff, one question. Your article is really interesting and concise, which adds value.

    BTW, is there any way to get the "desktop" dimensions in Linux/Unix?

  2. 2. At 7:50 a.m. on 5 jun 2007, Alexander Belchenko (the author) said:

    I'm not very good in Linux programming, but in the Bazaar VCS sources used such approach to get width of terminal:

    def terminal_width():
        """Return estimated terminal width."""
        width = 0
        try:
            import struct, fcntl, termios
            s = struct.pack('HHHH', 0, 0, 0, 0)
            x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
            width = struct.unpack('HHHH', x)[1]
        except IOError:
            pass
        if width <= 0:
            try:
                width = int(os.environ['COLUMNS'])
            except:
                pass
        if width <= 0:
            width = 80
    
        return width
    

    I hope this helps.

Sign in to comment