~ubuntu-branches/ubuntu/karmic/pypy/karmic

« back to all changes in this revision

Viewing changes to py/misc/terminal_helper.py

  • Committer: Bazaar Package Importer
  • Author(s): Alexandre Fayolle
  • Date: 2007-04-13 09:33:09 UTC
  • Revision ID: james.westby@ubuntu.com-20070413093309-yoojh4jcoocu2krz
Tags: upstream-1.0.0
ImportĀ upstreamĀ versionĀ 1.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import sys, os
 
2
 
 
3
def get_terminal_width():
 
4
    try:
 
5
        import termios,fcntl,struct
 
6
        call = fcntl.ioctl(0,termios.TIOCGWINSZ,"\000"*8)
 
7
        height,width = struct.unpack( "hhhh", call ) [:2]
 
8
        terminal_width = width
 
9
    except (SystemExit, KeyboardInterrupt), e:
 
10
        raise
 
11
    except:
 
12
        # FALLBACK
 
13
        terminal_width = int(os.environ.get('COLUMNS', 80))-1
 
14
    return terminal_width
 
15
 
 
16
terminal_width = get_terminal_width()
 
17
 
 
18
def ansi_print(text, esc, file=None, newline=True, flush=False):
 
19
    if file is None:
 
20
        file = sys.stderr
 
21
    text = text.rstrip()
 
22
    if esc and sys.platform != "win32" and file.isatty():
 
23
        if not isinstance(esc, tuple):
 
24
            esc = (esc,)
 
25
        text = (''.join(['\x1b[%sm' % cod for cod in esc])  +  
 
26
                text +
 
27
                '\x1b[0m')     # ANSI color code "reset"
 
28
    if newline:
 
29
        text += '\n'
 
30
    file.write(text)
 
31
    if flush:
 
32
        file.flush()
 
33
 
 
34