source: trunk/anuga_core/source/anuga/utilities/terminal_width.py @ 7876

Last change on this file since 7876 was 6909, checked in by rwilson, 15 years ago

Added terminal_width.py file.

File size: 1.8 KB
Line 
1#!/usr/bin/env python
2'''Function to get terminal width, Windows or Linux.'''
3
4######
5# This code was found at http://code.activestate.com/recipes/440694/
6#
7# Any errors here are mine, as the code below changed the code found above.
8######
9
10##
11# @brief Get the current terminal width.
12# @return The terminal width in characters.
13# @note If the width cannot be found, return 80 as a default.
14def terminal_width():
15    # First, try Windows.
16    try:
17        # fails if not Windows
18        from ctypes import windll, create_string_buffer
19
20        # stdin handle is -10
21        # stdout handle is -11
22        # stderr handle is -12
23        h = windll.kernel32.GetStdHandle(-12)
24        csbi = create_string_buffer(22)
25        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
26
27        if res:
28            import struct
29            (bufx, bufy, curx, cury, wattr, left,
30             top, right, bottom, maxx, maxy) = \
31                    struct.unpack("hhhhHhhhhhh", csbi.raw)
32            width = right - left + 1
33        else:
34            width = 80      # can't determine size - return default values
35    # No, try Linux
36    except:
37        width = 0
38        try:
39            import struct, fcntl, termios
40
41            s = struct.pack('HHHH', 0, 0, 0, 0)
42            x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
43            width = struct.unpack('HHHH', x)[1]
44        except (IOError, ImportError):
45            pass
46        if width <= 0:
47            try:
48                width = int(os.environ['COLUMNS'])
49            except:
50                pass
51        if width <= 0:
52            width = 80      # can't determine size - return default values
53
54    return width
55
56if __name__ == '__main__':
57    print 'terminal width=%d' % terminal_width()
Note: See TracBrowser for help on using the repository browser.