3

I've got a color from user in #RRGGBB hex format (#D3D3D3 is light grey) and I'd like to color some output with it. I imagine I write print("some text", color="#0000FF") and get blue colored output. Is it possible (ideally without 3rd party software)?

M. Volf
  • 1,259
  • 11
  • 29
  • 2
    Possible duplicate of [How do I print colored output to the terminal in Python?](https://stackoverflow.com/questions/37340049/how-do-i-print-colored-output-to-the-terminal-in-python) – Arpit Solanki Aug 20 '17 at 13:42
  • It depends. Truecolor ansi escapes are supported by some Unix/Linux terminal emulators. Where are you needing these? – Antti Haapala -- Слава Україні Aug 20 '17 at 13:45
  • @AnttiHaapala I'm working on program that gets photo and prints it as ASCII art. Using Ubuntu. – M. Volf Aug 20 '17 at 13:54
  • Possible duplicate of [Print in terminal with colors using Python?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python) – wwii Aug 20 '17 at 14:10

1 Answers1

9

You can use the following escape sequences on a true-color aware terminal:

  • ESC[ … 38;2;<r>;<g>;<b> … m Select RGB foreground color
  • ESC[ … 48;2;<r>;<g>;<b> … m Select RGB background color

Thus you can write a function:

RESET = '\033[0m'
def get_color_escape(r, g, b, background=False):
    return '\033[{};2;{};{};{}m'.format(48 if background else 38, r, g, b)

and use this like:

print(get_color_escape(255, 128, 0) 
      + get_color_escape(80, 30, 60, True)
      + 'Fancy colors!' 
      + RESET)

You can get doubled horizontal or vertical resolution by using for example and both background and foreground colour.

  • Not working for me, but it looks like I don't have _true-color aware terminal_ (LXTerminal). Will try it in somewhere else and then maybe accept answer. Btw. this is good test of your terminal: https://askubuntu.com/a/790991 – M. Volf Aug 21 '17 at 09:41