Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@martin-ueding
Created November 3, 2012 11:04
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save martin-ueding/4007035 to your computer and use it in GitHub Desktop.
Save martin-ueding/4007035 to your computer and use it in GitHub Desktop.
Python Colorcodes class
class Colorcodes(object):
"""
Provides ANSI terminal color codes which are gathered via the ``tput``
utility. That way, they are portable. If there occurs any error with
``tput``, all codes are initialized as an empty string.
The provides fields are listed below.
Control:
- bold
- reset
Colors:
- blue
- green
- orange
- red
:license: MIT
"""
def __init__(self):
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:
self.bold = ""
self.reset = ""
self.blue = ""
self.green = ""
self.orange = ""
self.red = ""
_c = Colorcodes()
@niun
Copy link

niun commented Aug 27, 2022

Thanks, this helped me :)
For Python 3 add .decode('latin1') to the check_output's output to translate the byte sequence 1:1 to an 8 bit character string:

self.red = subprocess.check_output("tput setaf 1".split()).decode('latin1')

@deekb
Copy link

deekb commented Sep 8, 2022

I got:

tput: No value for $TERM and no -T specified

Linux Mint 20.3 (Cinnamon 5.2.7)
Python 3.8

@martin-ueding
Copy link
Author

@niun: You don't need to specify latin1, because hopefully it is utf8. Just use .decode().

@deekb: Make sure you have a sensible value for $TERM, like xterm-256color. Perhaps set it in your .bashrc with export TERM=xterm-256color.

@deekb
Copy link

deekb commented Sep 20, 2022

got it, looks like I was using thonny and had not set it up correctly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment