Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color Python output given #RRGGBB hex value

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)?

like image 642
M. Volf Avatar asked Oct 19 '25 21:10

M. Volf


1 Answers

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.

like image 105


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!