Output color characters to pretty with python

Overview

There was an article about pretty print in color, and I wondered what to do with python, so I searched for parts with stackoverflow and wrote it by imitating it.

pp.png

For the time being, I read the yaml file and displayed the result of parsing.

How to use

python pp.py <file name>  [Number of indents]

Like this

pp.png

pp.py


# -*- coding: utf-8 -*-

class color:
    BLUE = '\033[1;34m'
    BLUEL = '\033[0;34m'
    GREEN = '\033[1;32m'
    GREENL = '\033[0;32m'
    CYAN = '\033[1;36m'
    CYANL = '\033[0;36m'
    RED = '\033[1;31m'
    REDL = '\033[0;31m'
    PURPLE = '\033[1;35m'
    PURPLEL = '\033[0;35m'
    YELLOW = '\033[1;33m'
    BROWN = '\033[0;33m'
    WHITE = '\033[1;37m'
    GRAYL = '\033[0;37m'
    GRAYD = '\033[1;30m'
    BLACK = '\033[0;30m'
    ENDC = '\033[0m'

def pretty_convert(obj):
    if isinstance(obj, (float)):
        return u'{1}{2}{0}'.format(color.ENDC, color.PURPLEL, obj)
    elif isinstance(obj, ( bool )):
        return u'{1}{2}{0}'.format(color.ENDC, color.CYAN, obj)
    elif isinstance(obj, ( int, long, complex )):
        return u'{1}{2}{0}'.format(color.ENDC, color.BLUE, obj)
    elif isinstance(obj, ( basestring )):
        return u'{1}"{0}{2}{3}{0}{1}"{0}'.format(color.ENDC, color.REDL, color.RED, obj)
    elif isinstance(obj, ( dict )):
        return dict((u'{1}{2}:{0}'.format(color.ENDC, color.YELLOW,k), pretty_convert(v)) for k, v in obj.items())
    elif isinstance(obj, (list, tuple)):
        return map(pretty_convert, obj)
    return obj

def walk_obj(buf, obj, indent_num=2, depth=0, eol='', wrap_len=60, wrap_total=100, lf='\n'):
    indent = ' '*indent_num*depth
    buf.write(u'{0}'.format(eol if not eol else eol+indent) )
    if isinstance(obj, (basestring, int, float, complex)):
        buf.write(u'{0}'.format(obj).replace(lf, '{0}{1} '.format(lf, indent)) )
    elif isinstance(obj, ( dict )):
        eol, eol_org = lf, eol
        buf.write('{ ')
        for key in obj.keys():
            buf.write(u'{0}{1}{2}{3} '.format(eol, indent, ' '*indent_num, key))
            walk_obj(buf=buf, obj=obj[key], indent_num=indent_num, depth=depth+1, eol='', wrap_len=wrap_len, lf=lf )
            buf.write(',')
        buf.write('{0}}}'.format(eol if not eol else eol+indent) )
        eol=eol_org
    elif isinstance(obj, (list, tuple)):
        eol_org, indent_org = eol, indent
        for item in obj:
            if isinstance(item, (list, dict)):
                eol = lf
                break
            else:
                eol = ''
                indent = ''
                continue
        if max(map(len,obj)) > wrap_len or sum(map(len,obj)) > wrap_total:
            eol = lf
        buf.write('[ ')
        for item in obj:
            walk_obj(buf=buf, obj=item, indent_num=indent_num, depth=depth+1, eol=eol, wrap_len=wrap_len, lf=lf )
            buf.write(', ')
        buf.write('{0}]'.format(eol if not eol else eol+indent_org) )
        eol, indent = eol_org, indent_org
    if depth == 0:
        buf.write(lf)

def pretty_print(obj, indent=2, b=None):
    if not b:
        import sys, codecs
        b = codecs.getwriter('utf_8')(sys.stdout)
    walk_obj(b, pretty_convert(obj), indent_num=indent)


if __name__ == '__main__':
  import sys
  import codecs
  import yaml
  import pprint

  if len(sys.argv) < 2:
     print 'yaml file name is needed'
     sys.exit(2)
  indent = 2 if len(sys.argv) <3 else int(sys.argv[2])

  sys.stdout = codecs.getwriter('utf_8')(sys.stdout)

  file = codecs.open(sys.argv[1], 'r', 'utf_8').read()

  sys.stdout.write('# file \n\n```\n')
  sys.stdout.write(file)

  contents = yaml.load(file)

  sys.stdout.write('\n```\n\n# pprint.PrettyPrinter \n\n```\n\n')
  pp=pprint.PrettyPrinter(indent=indent)
  pp.pprint(contents)

  sys.stdout.write('\n```\n\n# pretty_print \n\n```\n')
  pretty_print(contents, indent, sys.stdout)
  sys.stdout.write('\n')

zz.yml


dictionary:
  - { test: this is test, test2: 1, test3: true }
  - [1,2,3,4,5]
 ――――'Play with Nihongo'
 -[6,7,8,9,'test']
  - name: test
 Name: test2
  - test2
  - test3
  - true
  - 65535
  - 3.14
  - - list1
    - list2
    - list3
list:
  -  name: this is dictionary,
     bool: false
     int: 15000
     float: 15.6
     list: [ 0,1,2,3,4 ]
  - "this is test"
  - |
    this is test
    this is Test
    this is tesT

Recommended Posts

Output color characters to pretty with python
Output to csv file with Python
Try to reproduce color film with Python
Output Python log to console with GAE
Segfault Python with 33 characters
I tried to output LLVM IR with Python
How to erase the characters output by Python
[Python] How to handle Japanese characters with openCV
Connect to BigQuery with Python
Procedure to load MNIST with python and output to png
Try Python output with Haxe 3.2
Connect to Wikipedia with Python
Post to slack with Python 3
Output to syslog with Loguru
Pretty print json or yaml with color in python
Switch python to 2.7 with alternatives
Write to csv with Python
[Python-pptx] Output PowerPoint font information to csv with python
Link to get started with python
Create folders from '01' to '12' with python
Nice to meet you with python
Try to operate Facebook with Python
Input / output with Python (Python learning memo ⑤)
Convert list to DataFrame with python
Output cell to file with Colaboratory
MP3 to WAV conversion with Python
To do tail recursion with Python2
How to get started with Python
[Note] Hello world output with python
Unit test log output with python
What to do with PYTHON release?
Unable to install Python with pyenv
How to use FTP with Python
[Python] One-liner Stalin sort with 50 characters
How to calculate date with python
Easily post to twitter with Python 3
Try to output audio with M5STACK
I want to debug with Python
Convert to a string while outputting standard output with Python subprocess
I want to output the beginning of the next month with Python
Output the contents of ~ .xlsx in the folder to HTML with Python
[Python] Try to recognize characters from images with OpenCV and pyocr
Change Python 64bit environment to 32bit environment with Anaconda
English speech recognition with python [speech to text]
Convert memo at once with Python 2to3
HTML email with image to send with python
Python to remember only with hello, worlds
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
Fractal to make and play with Python
I wanted to solve ABC160 with Python
Connect to MySQL with Python within Docker
How to work with BigQuery in Python
[Introduction to Python] Let's use foreach with Python
Single pixel camera to experience with Python
[Python] Introduction to CNN with Pytorch MNIST
Convert FX 1-minute data to 5-minute data with Python
I want to analyze logs with Python
How to do portmanteau test with python
I want to play with aws with python