Wrapper when you want to output utf-8 + ansi color on Windows console

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import subprocess

reload(sys) 
sys.setdefaultencoding("utf-16")

HAS_COLORAMA = True

try:
  import colorama
  colorama.init()
except:
  HAS_COLORAMA = False

p = subprocess.Popen(sys.argv[1:], stdout=subprocess.PIPE)

def decode_ansi(s):
  assert s[0] == '[', "string does not start with control sequence"
  for i in range(1, len(s)):
    if s[i] == 'm':
      break

  return s[i+1:], s[1:i].split(';')

for line in p.stdout:
  substrs = line.split(chr(27))
  sys.stdout.write(substrs[0].decode('utf-8'))
  for s in substrs[1:]:
    s, cs = decode_ansi(s)
    if HAS_COLORAMA:
      sys.stdout.write("\033[%sm" % ';'.join(cs))
    sys.stdout.write(s.decode('utf-8'))

Recommended Posts

Wrapper when you want to output utf-8 + ansi color on Windows console
When you want to use python2.x on modern Gentoo Linux
When you want to hit a UNIX command on Python
I want to output to the console coolly
If you want to use NumPy, Pandas, Matplotlib, IPython, SciPy on Windows
When you want to update the chrome driver.
I want to do pyenv + pipenv on Windows
What to do when you want to receive files from a Windows client remotely
If you get stuck when building pycocoapi on Windows
Settings when you want to run python-mecab with travis
Output log to console with Flask + Nginx on Docker
When you want to filter with Django REST framework
When you want to plt.save in a for statement
Solution when you want to use cv_bridge with python3 (virtualenv)
[Django] A memorandum when you want to communicate asynchronously [Python3]
[AWS] What to do when you want to pip with Lambda
Use aggdraw when you want to draw beautifully with pillow
When you want to register Django's initial data with relationships
[AWS EC2] Settings you want to do on Amazon Linux 2
When you want to keep the Sphinx documentation theme as usual
I want to know if you install Python on Mac ・ Iroha
[Python] When you want to use all variables in another file
When you want to save the result of the callback function somewhere
When you run diff in python and want both returncode and output
When you want to send an object with requests using flask
When you want to sort a multidimensional list by multiple lines
When you want to adjust the axis scale interval with APLpy