Last active
March 27, 2024 02:43
-
-
Save CTimmerman/ddb19887b7f5e36eea122deb5eaf7431 to your computer and use it in GitHub Desktop.
Rainbow terminal console text and/or background
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Rainbow print loop using ANSI escape sequences. Press Ctrl+C to stop. | |
By Cees Timmerman | |
2020-03-06 First version. | |
2024-03-27 Fixed on Windows 11.""" | |
import time | |
CSI = "\x1b[" # Control Sequence Introducer. | |
# https://en.wikipedia.org/wiki/ANSI_escape_code#Fe_Escape_sequences | |
# On Windows 11, C1 control code 155 "\x9b" only works the same in VS Code. | |
# https://github.com/microsoft/terminal/issues/10310 | |
RESET = CSI+"0m" | |
FGWHITE = CSI+"38;2;255;255;255m" | |
FGBLACK = CSI+"38;2;0;0;0m" # [30m isn't always black: https://en.wikipedia.org/wiki/ANSI_escape_code | |
s = 17 # 1, 3, 5, 15, 17, 51, 85, 255, or any integer between. | |
r = 255; g = 0; b = 0 | |
rs = 0; gs = s; bs = 0 | |
while True: | |
r += rs; g += gs; b += bs | |
if rs > 0 and r >= 255: r = 255; rs = 0; bs = -s | |
elif gs > 0 and g >= 255: g = 255; gs = 0; rs = -s | |
elif bs > 0 and b >= 255: b = 255; bs = 0; gs = -s | |
elif rs < 0 and r <= 0: r = 0; rs = 0; bs = s | |
elif gs < 0 and g <= 0: g = 0; gs = 0; rs = s | |
elif bs < 0 and b <= 0: b = 0; bs = 0; gs = s | |
foreground = CSI+f"38;2;{r};{g};{b}m" | |
background = CSI+f"48;2;{r};{g};{b}m" | |
text = f"({r: >3},{g: >3},{b: >3})" | |
#print(foreground + text) | |
#print(background + FGBLACK + text + RESET) | |
### Full line ### | |
#print(background+"\n"+FGBLACK+text, end="") | |
print(background+"\n"+RESET+foreground+text, end="") | |
#print(background) | |
time.sleep(0.02) |
To enable escape sequences in the Windows Command Prompt or PowerShell:
- Just add
|Out-Host
in PowerShell, e.g.py rainbow.py |Out-Host
- Or run this and restart PowerShell:
Set-ItemProperty HKCU:\Console VirtualTerminalLevel -Type DWORD 1
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://en.wikipedia.org/wiki/HSL_and_HSV#/media/File:HSV-RGB-comparison.svg said more than the rest of the article on how to not get a muddy spectrum yellow described here.