Reputation: 1482
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)?
Upvotes: 4
Views: 8635
Reputation: 134038
You can use the following escape sequences on a true-color aware terminal:
ESC[ … 38;2;<r>;<g>;<b> … m
Select RGB foreground colorESC[ … 48;2;<r>;<g>;<b> … m
Select RGB background colorThus 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.
Upvotes: 10