File: ansi.py

package info (click to toggle)
espresso 6.7-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 311,068 kB
  • sloc: f90: 447,429; ansic: 52,566; sh: 40,631; xml: 37,561; tcl: 20,077; lisp: 5,923; makefile: 4,503; python: 4,379; perl: 1,219; cpp: 761; fortran: 618; java: 568; awk: 128
file content (51 lines) | stat: -rw-r--r-- 1,141 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'''
testcode2.ansi
--------------

(A subset of) ANSI codes and functions to wrap codes around strings.

:copyright: (c) 2012 James Spencer.
:license: modified BSD; see LICENSE for more details.
'''

import sys

ANSI_START = '\033['
ANSI_END = '\033[0m'

ANSI_SGR = dict(
            bold=1,
        )

ANSI_INTENSITY = dict(
            normal=0,
            bright=60,
        )

ANSI_COLOUR = dict(
            black=30,
            red=31,
            green=32,
            yellow=33,
            blue=34,
            magenta=35,
            cyan=36,
            white=37,
        )

def ansi_format(string, colour='black', intensity='normal', style=None,
                override=False):
    '''Return string wrapped in the appropriate ANSI codes.

Note: if not writing to a true terminal and override is false, then the string
is not modified.
'''

    if sys.stdout.isatty() or override:
        code = str(ANSI_COLOUR[colour]+ANSI_INTENSITY[intensity])
        if style:
            code += ';%s' % (ANSI_SGR[style])
        code += 'm'
        return ANSI_START + code + string + ANSI_END + ANSI_END
    else:
        return string