1185.16.86
by mbp at sourcefrog
- win32 get_console_size from Alexander |
1 |
"""
|
2 |
Set of functions to work with console on Windows.
|
|
3 |
Author: Alexander Belchenko (e-mail: bialix AT ukr.net)
|
|
4 |
License: Public domain
|
|
5 |
"""
|
|
6 |
||
7 |
import struct |
|
8 |
||
9 |
# We can cope without it; use a separate variable to help pyflakes
|
|
1773.4.1
by Martin Pool
Add pyflakes makefile target; fix many warnings |
10 |
try: |
1185.16.86
by mbp at sourcefrog
- win32 get_console_size from Alexander |
11 |
import ctypes |
12 |
has_ctypes = True |
|
1773.4.1
by Martin Pool
Add pyflakes makefile target; fix many warnings |
13 |
except ImportError: |
1185.16.86
by mbp at sourcefrog
- win32 get_console_size from Alexander |
14 |
has_ctypes = False |
1773.4.1
by Martin Pool
Add pyflakes makefile target; fix many warnings |
15 |
|
1185.16.86
by mbp at sourcefrog
- win32 get_console_size from Alexander |
16 |
|
17 |
WIN32_STDIN_HANDLE = -10 |
|
1704.2.3
by Martin Pool
(win32) Detect terminal width using GetConsoleScreenBufferInfo (Alexander) |
18 |
WIN32_STDOUT_HANDLE = -11 |
19 |
WIN32_STDERR_HANDLE = -12 |
|
20 |
||
21 |
||
22 |
def get_console_size(defaultx=80, defaulty=25): |
|
1185.16.86
by mbp at sourcefrog
- win32 get_console_size from Alexander |
23 |
""" Return size of current console.
|
24 |
||
25 |
This function try to determine actual size of current working
|
|
26 |
console window and return tuple (sizex, sizey) if success,
|
|
27 |
or default size (defaultx, defaulty) otherwise.
|
|
28 |
||
29 |
Dependencies: ctypes should be installed.
|
|
30 |
"""
|
|
31 |
if not has_ctypes: |
|
1773.4.1
by Martin Pool
Add pyflakes makefile target; fix many warnings |
32 |
# no ctypes is found
|
1185.16.86
by mbp at sourcefrog
- win32 get_console_size from Alexander |
33 |
return (defaultx, defaulty) |
34 |
||
35 |
# To avoid problem with redirecting output via pipe
|
|
1704.2.3
by Martin Pool
(win32) Detect terminal width using GetConsoleScreenBufferInfo (Alexander) |
36 |
# need to use stderr instead of stdout
|
37 |
h = ctypes.windll.kernel32.GetStdHandle(WIN32_STDERR_HANDLE) |
|
38 |
csbi = ctypes.create_string_buffer(22) |
|
1185.16.86
by mbp at sourcefrog
- win32 get_console_size from Alexander |
39 |
res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) |
40 |
||
41 |
if res: |
|
42 |
(bufx, bufy, curx, cury, wattr, |
|
43 |
left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) |
|
44 |
sizex = right - left + 1 |
|
45 |
sizey = bottom - top + 1 |
|
46 |
return (sizex, sizey) |
|
47 |
else: |
|
48 |
return (defaultx, defaulty) |
|
49 |