Can ANSI escape code SGR 38 - Set foreground color with argument 2;r;g;b be used with print function? Example of use with code 33 is of course
OKBLUE = '\033[94m'
I would like to use 038 instead to be able to use any RGB color. Is that posible?
I tried
GREEN = '\038[2;0;153;0m'
ENDC = '\033[0m'
print(f"{GREEN} some text {ENDC}")
Expected to change the color of "some text" in green
To use an RGB color space within the terminal* the following escape sequence can be used:
# Print Hello! in lime green text.
print('\033[38;2;146;255;12mHello!\033[0m')
# ^
# |
# \ The 38 goes here, to indicate a foreground colour.
# Print Hello! in white text on a fuschia background.
print('\033[48;2;246;45;112mHello!\033[0m')
Explanation:
\033[38;2;146;255;12mHello!\033[0m
^ ^ ^ ^ ^ ^ ^ ^ ^
| | | R G B | | |
| | | | | | \ Reset the colour to default
| | | | | |
| | | | | \ Escape character
| | | | |
| | | \ R;G;B \ Text to print
| | |
| | \ Indicate the following sequence is RGB
| |
| \ Code to instruct the setting of an 8 or 24-bit foreground (text) colour
|
\ Escape character
The use of 38;2
indicates an RGB (foreground) sequence is to follow. However, the use of 38;5
indicates the following (foreground) value comes from the 256-colour table.
To clarify what appears to be a misconception, \033
(octal) or \x1b
(hexidecimal) corresponds to the ASCII table's ESC character, which is used here to introduce an escape sequence of terminal text colouring. Whereas the 38
is used to instruct the following 8 or 24-bit colour to be set as foreground, (after the escape sequence has been introduced). Additionally, 48
can be used to set the background colour, as demonstrated in the code example above.
*Providing the terminal emulator supports 24-bit colour sequences. (e.g. Xterm, GNOME terminal, etc.)
Link to the Wikipedia article which explains this topic of 24-colour (RGB) in greater depth.