Skip to content

Instantly share code, notes, and snippets.

@Julian-Nash
Last active December 26, 2022 00:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Julian-Nash/83dc19ecfc698ae07d1b5fd73fba4541 to your computer and use it in GitHub Desktop.
Save Julian-Nash/83dc19ecfc698ae07d1b5fd73fba4541 to your computer and use it in GitHub Desktop.
Print colored objects in the console depending on their type. Useful for development & debugging requests.
import click
import json
def cprint(x=None):
"""
Pass any object into cprint to have it printed to the console in color!
json = yellow (json is pretty printed by default)
Python collections [list, dict, tuple] = green
Integers & floats = magenta
Other = red
:param x:
:return: None
"""
if x == None:
click.secho("No data was passed to cprint", fg="red", bold=True)
return None
# json
if type(x) == str:
try:
json_test = json.loads(x)
pretty_json = json.dumps(json_test, indent=2)
click.secho('\n{}'.format(pretty_json), fg='yellow', bold=True)
except ValueError:
click.secho('\n{}'.format(x), fg='cyan', bold=True)
# list
elif type(x) == list:
click.secho('\n{}'.format(x), fg='green', bold=True)
# dict
elif type(x) == dict:
click.secho('\n{}'.format(x), fg='green', bold=True)
# tuple
elif type(x) == tuple:
click.secho('\n{}'.format(x), fg='green', bold=True)
# int
elif type(x) == int:
click.secho('\n{}'.format(x), fg='magenta', bold=True)
# float
elif type(x) == float:
click.secho('\n{}'.format(x), fg='magenta', bold=True)
# other
else:
click.secho('\n{}'.format(x), fg='red', bold=True)
@Julian-Nash
Copy link
Author

Julian-Nash commented Mar 3, 2018

Console color printer


Quick & dirty function I've been using in Flask development.

Print colored objects in the console depending on their type. Useful for development & debugging requests.

Uses click by Armin Ronacher -> @mitsuhiko

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment