Welcome, guest | Sign In | My Account | Store | Cart

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, 20 lines
 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

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.

2 comments

Ernesto Savoretti 15 years, 8 months ago  # | flag

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?

Alexander Belchenko (author) 15 years, 2 months ago  # | flag

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.