"""Generic pretty display utils.This module defines a print function that's supposed to be able to pretty-printanything, as well as a pretty diff printer."""importosNO_COLOR=bool(os.getenv('NO_COLOR',''))_print=printdefhighlight(string,lexer):ifNO_COLOR:returnstringtry:importpygmentsimportpygments.lexersimportpygments.formattersexceptImportError:returnstringformatter=pygments.formatters.TerminalFormatter()lexer=getattr(pygments.lexers,lexer+'Lexer')()returnpygments.highlight(string,lexer,formatter)defyaml_dump(data):importyamlifisinstance(data,dict):# ensure that objects inheriting from dict render nicelydata=dict(data)returnyaml.dump(data,indent=4,width=float('inf'))defyaml_highlight(yaml_string):returnhighlight(yaml_string,'Yaml')
[docs]defprint(*args,**kwargs):""" Try to print the args, pass the kwargs to actual print method. If any arg is parseable as JSON then it'l be parsed. Then, it'll be dumped as colored YAML. Set the env var `NO_COLORS` to anything to prevent `cli2.print` from printing colors. .. code-block:: python import cli2 # pretty print some_object cli2.print(some_object) This outputs colors by default, set the env var `NO_COLORS` to anything to prevent printing colors. """try:importjsonlightasjsonexceptImportError:importjsonforarginargs:try:# deal with response objectsarg=arg.json()except(TypeError,AttributeError):passtry:# is this json?arg=json.loads(arg)except:# noqapassstring=argifisinstance(arg,str)elseyaml_dump(arg)_print(yaml_highlight(string),**kwargs)