Using ansicolors:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# colourshen.py - stdin to rainbow stdout
# scruss, 2020-06
from colors import * # see https://pypi.org/project/ansicolors/
import sys
wheel_pos = 0
def cos_wheel(pos):
# Input a value 0 to 255 to get a colour value.
# scruss (Stewart Russell) - 2019-03 - CC-BY-SA
from math import cos, pi
if pos < 0:
return (0, 0, 0)
pos %= 256
pos /= 255.0
return (int(255 * (1 + cos(pos * 2 * pi)) / 2),
int(255 * (1 + cos((pos - 1 / 3.0) * 2 * pi)) / 2),
int(255 * (1 + cos((pos - 2 / 3.0) * 2 * pi)) / 2))
def hex_wheel(pos):
rgb = cos_wheel(pos)
return('#%02x%02x%02x' % rgb)
def wheel_print(s):
global wheel_pos
incr = int(256/(1+len(s)))-1
if incr < 1:
incr = 1
for c in s:
print(color(c, fg=hex_wheel(wheel_pos)), end='')
wheel_pos = (wheel_pos+incr) % 256
print()
for txt in sys.stdin:
wheel_print(txt.rstrip())
(fixed a very obvious ahem! in the code, hope no-one noticed …)