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.
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.
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?
I'm not very good in Linux programming, but in the Bazaar VCS sources used such approach to get width of terminal:
I hope this helps.