LoginSignup
4
4

More than 5 years have passed since last update.

Windowsのconsoleでutf-8 + ansi colorを出力したいときのラッパー

Posted at
#!/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'))
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4