Sortir les caractères de couleur en joli avec python

Aperçu

Il y avait un article sur la jolie impression en couleur, et je me demandais quoi faire avec python, alors j'ai recherché des pièces avec stackoverflow et l'ai écrit en l'imitant.

pp.png

Pour le moment, j'ai lu le fichier yaml et affiché le résultat de l'analyse.

Comment utiliser

python pp.py <nom de fichier>  [Nombre de retraits]

Comme ça

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]
 ―――― «Jouez avec le japonais»
 - [6,7,8,9, "test"]
  - name: test
 Nom: 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

Sortir les caractères de couleur en joli avec python
Sortie vers un fichier csv avec Python
Essayez de reproduire un film couleur avec Python
Sortie du journal Python vers la console avec GAE
Segfo Python avec 33 caractères
J'ai essayé de sortir LLVM IR avec Python
Comment effacer les caractères générés par Python
[Python] Comment gérer les caractères japonais avec openCV
Connectez-vous à BigQuery avec Python
Procédure pour charger MNIST avec python et sortie en png
Essayez la sortie Python avec Haxe 3.2
Connectez-vous à Wikipedia avec Python
Publiez sur Slack avec Python 3
Joli imprimé json ou yaml avec couleur en python
Basculer python vers 2.7 avec des alternatives
Écrire en csv avec Python
[Python-pptx] Afficher les informations de police PowerPoint au format csv avec python
Lien pour commencer avec python
Ravi de vous rencontrer avec python
Essayez d'exploiter Facebook avec Python
Entrée / sortie avec Python (mémo d'apprentissage Python ⑤)
Convertir la liste en DataFrame avec python
Conversion MP3 → WAV avec Python
Pour faire une récursion avec Python2
Comment démarrer avec Python
[Note] Sortie Hello world avec python
Sortie du journal de test unitaire avec python
Que faire avec la sortie de PYTHON?
[Python] Tri Starlin à une ligne avec 50 caractères
Comment calculer la date avec python
Publiez facilement sur Twitter avec Python 3
Essayez de produire de l'audio avec M5 STACK
Je veux déboguer avec Python
Convertir en chaîne lors de la sortie de la sortie standard avec le sous-processus Python
Je veux sortir le début du mois prochain avec Python
Exportez le contenu de ~ .xlsx dans le dossier en HTML avec Python
[Python] Essayez de reconnaître les caractères des images avec OpenCV et pyocr
Changer l'environnement Python 64 bits en environnement 32 bits avec Anaconda
Reconnaissance vocale en anglais avec python [speech to text]
Convertir un mémo à la fois avec Python 2to3
mail html avec image à envoyer avec python
python à retenir uniquement avec bonjour, mondes
Introduction au remplissage d'image Python Remplissage d'image à l'aide d'ImageDataGenerator
Convertir des données Excel en JSON avec python
Convertir Hiragana en Romaji avec Python (bêta)
Fractal pour faire et jouer avec Python
Je voulais résoudre ABC160 avec Python
Connectez-vous à MySQL avec Python dans Docker
Comment utiliser BigQuery en Python
[Introduction à Python] Utilisons foreach avec Python
Caméra à pixel unique à expérimenter avec Python
Convertissez des données FX 1 minute en données 5 minutes avec Python
Je veux analyser les journaux avec Python
Comment faire un test de sac avec python
Je veux jouer avec aws avec python