This is How You Color Print Out in Python
Many Python programmers depend on printing out statements on console, as a GUI isn’t always necessary. The issue sometimes is that a black and white console doesn’t help much when one has several console windows opened and running different functions. For example:
Honestly, you are not going to see what’s wrong (or right) easily when everything is just white on a black background.
So here it comes a library to help us out, fortunately! It’s called Termcolor. So let’s install it via python -m pip install termcolor command.
How to use it
It’s pretty simple. As simples as Python.
from termcolor import coloredprint(colored('Hello', 'red'), colored('Medium', 'yellow'), colored('world', 'green'))
Before and after
Using try and except
from termcolor import coloredtry:
int('Hello World')
print(colored('Success!', 'green'))
except Exception as E:
print(colored(str(E), 'red'))
from termcolor import coloredtry:
int('10')
print(colored('Success!', 'green'))
except Exception as E:
print(colored(str(E), 'red'))
Printing an exception in color and bold
from termcolor import colored, cprint
import systry:
int('Hello World')
print(colored('Success!', 'green'))
except Exception as E:
cprint(str(E), 'red', attrs=['bold'], file=sys.stderr)
Printing try and exception in red and green backgrounds
from termcolor import colored, cprinttry:
int('Hello World')
print(colored('Success', 'green', attrs=['reverse', 'blink']))
except Exception as E:
print(colored(str(E), 'red', attrs=['reverse', 'blink']))
from termcolor import colored, cprinttry:
int('10')
print(colored('Success', 'green', attrs=['reverse', 'blink']))
except Exception as E:
print(colored(str(E), 'red', attrs=['reverse', 'blink']))
Conclusion
This library definitely helps us easily checking what’s going on in the code and on the console window without much effort, by just adapting the print statement a bit.
Have you ever used any of these? Please let me know in the comments. You can also follow me here, so you can track what’s next to come.
I hope you enjoyed this article.
More content at plainenglish.io