Create a gist now

Instantly share code, notes, and snippets.

@gynter /ansi_sgr.py
Last active Aug 29, 2015

What would you like to do?
ANSI SGR for text terminal
# -*- coding: utf-8 -*-
"""
Copyright (c) 2015 Günter Kits
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Example:
# -*- coding: utf-8 -*-
from ansi_sgr import *
for idx, code in enumerate(CODE_MAP):
if code:
print ftt(code, idx)
"""
from sys import stdout
# ANSI SGR (Select Graphic Rendition) code map.
# Not defined here: 38, 48, 90-99 (not in standard), 100-109 (not in
# standard).
CODE_MAP = ('NORMAL', 'BOLD', 'FAINT', 'ITALIC', 'UNDERLINE',
'BLINK', 'RAPID-BLINK', 'NEGATIVE', 'CONCEAL', 'CROSSED-OUT',
'FONT-DEFAULT', 'FONT-1', 'FONT-2', 'FONT-3', 'FONT-4', 'FONT-5',
'FONT-6', 'FONT-7', 'FONT-8', 'FONT-9', 'FRAKTUR',
'DOUBLE-UNDERLINE', 'NO-BOLD', 'NO-ITALIC', 'NO-UNDERLINE',
'NO-BLINK', False, 'POSITIVE', 'REVEAL', 'NO-CROSSED-OUT',
'BLACK', 'RED', 'GREEN', 'YELLOW', 'BLUE', 'MAGENTA', 'CYAN',
'WHITE', False, 'DEFAULT', 'BG-BLACK', 'BG-RED', 'BG-GREEN',
'BG-YELLOW', 'BG-BLUE', 'BG-MAGENTA', 'BG-CYAN', 'BG-WHITE', False,
'BG-DEFAULT', False, 'FRAMED', 'ENCIRCLED', 'OVERLINED',
'NO-FRAMED', 'NO-OVERLINED', False, False, False, False,
'IDG-UNDERLINE', 'IDG-DOUBLE-UNDERLINE', 'IDG-OVERLINE',
'IDG-DOUBLE-OVERLINE', 'IDG-STRESS')
def ansi_escape(*codes):
def translate(code=0):
if isinstance(code, int):
return code
elif code:
if code in CODE_MAP:
return CODE_MAP.index(code)
else:
raise ValueError("Code string '%s' not in code map" % (code,))
else:
return False
def make(*sgr_codes):
sgr = []
for code in sgr_codes:
if code is False:
continue
if not isinstance(code, int):
raise TypeError("Must be integer, got '%s' instead" % (type(code).__name__,))
elif code < 0 or code > 64:
raise ValueError("Illegal ANSI code %d" % (code,))
sgr.append(str(code))
sgr = ';'.join(sgr)
return ''.join(['[', sgr, 'm'])
if not codes: codes = (0,)
return make(*map(lambda c: translate(c), codes))
def format_text_terminal(s, *codes):
if stdout.isatty():
return ''.join(['\x1b', ansi_escape(*codes), s, '\x1b', ansi_escape(0)])
else:
return s
ftt = format_text_terminal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment