Skip to content

Instantly share code, notes, and snippets.

@housemaister
Forked from 0xjairo/colorcodes.py
Last active January 20, 2022 02:02
Show Gist options
  • Save housemaister/5255959 to your computer and use it in GitHub Desktop.
Save housemaister/5255959 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 = ""
self.purple = ""
self.cyan = ""
self.white = ""
self.grey = ""
# 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())
self.purple = subprocess.check_output("tput setaf 5".split())
self.cyan = subprocess.check_output("tput setaf 6".split())
self.white = subprocess.check_output("tput setaf 7".split())
self.grey = subprocess.check_output("tput setaf 8".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