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

Last change on this file since 8813 was 8146, checked in by wilsonr, 14 years ago

Removed '@brief' comments.

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
10def terminal_width():
11    """Get the current terminal width.
12
13    Returns the terminal width in characters.
14
15    If the width cannot be found, return 80 as a default.
16    """
17
18    # First, try Windows.
19    try:
20        # fails if not Windows
21        from ctypes import windll, create_string_buffer
22
23        # stdin handle is -10
24        # stdout handle is -11
25        # stderr handle is -12
26        h = windll.kernel32.GetStdHandle(-12)
27        csbi = create_string_buffer(22)
28        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
29
30        if res:
31            import struct
32            (bufx, bufy, curx, cury, wattr, left,
33             top, right, bottom, maxx, maxy) = \
34                    struct.unpack("hhhhHhhhhhh", csbi.raw)
35            width = right - left + 1
36        else:
37            width = 80      # can't determine size - return default values
38    # No, try Linux
39    except:
40        width = 0
41        try:
42            import struct, fcntl, termios
43
44            s = struct.pack('HHHH', 0, 0, 0, 0)
45            x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
46            width = struct.unpack('HHHH', x)[1]
47        except (IOError, ImportError):
48            pass
49        if width <= 0:
50            try:
51                width = int(os.environ['COLUMNS'])
52            except:
53                pass
54        if width <= 0:
55            width = 80      # can't determine size - return default values
56
57    return width
58
59if __name__ == '__main__':
60    print 'terminal width=%d' % terminal_width()
Note: See TracBrowser for help on using the repository browser.