Skip to content

Instantly share code, notes, and snippets.

@0xjairo
Forked from martin-ueding/colorcodes.py
Last active January 20, 2022 02:02
Show Gist options
  • Save 0xjairo/5169803 to your computer and use it in GitHub Desktop.
Save 0xjairo/5169803 to your computer and use it in GitHub Desktop.
import os
import subprocess
class Colorcodes(object):
"""
Provides ANSI terminal color codes which are gathered via the ``tput``
utility. That way, they are portable. Color codes are initialized to
empty strings. If the output is being redirected or if there occurs
any error with ``tput``, keep empty strings.
The provided fields are listed below.
Control:
- bold
- reset
Colors:
- blue
- green
- orange
- red
:license: MIT
"""
def __init__(self):
# default to no colorizing
self.bold = ""
self.reset = ""
self.blue = ""
self.green = ""
self.orange = ""
self.red = ""
# check if redirecting output (i.e. redirecting to a file)
if os.fstat(0) != os.fstat(1): return
# try colorizing
try:
self.bold = subprocess.check_output("tput bold".split())
self.reset = subprocess.check_output("tput sgr0".split())
self.blue = subprocess.check_output("tput setaf 4".split())
self.green = subprocess.check_output("tput setaf 2".split())
self.orange = subprocess.check_output("tput setaf 3".split())
self.red = subprocess.check_output("tput setaf 1".split())
except subprocess.CalledProcessError as e:
pass
_c = Colorcodes()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment