Escape sequence on python

2021-02-17 python

Play with special ASCII codes on Python.

import random, sys, time

color = 91  # 90:gray, 91:red , 92:green, 93:yellow, 94:purple

while True:
  w = 60
  i = int(random.random() * w)
  sys.stderr.write("\033[%dm" % (color))
  sys.stderr.write('\r' + ('o' * i) + ' ' * (w-i))
  sys.stderr.write("\033[0m")
  sys.stderr.write(' ' + ('%02d' % (i)))
  sys.stderr.flush()
  time.sleep(0.3)

The result will be like the below.

% python3 sample.py
oooooooooooooooooooooooooooooooooooo                         36