I am trying to write for both NT and POSIX (my two usual platforms) and have come up with the code below. The clrs
code I refer to is apparently from blender build scripts, I discovered it on this SO post. They called the class bcolors
but I wanted to reduce clutter so I renamed it.
But the main class is what I've written that determines the os before printing. Prints are called, for example, via PRN.cyan("some string")
.
For this to work I import colorama
:
from colorama import init, Fore, Back, Style
init()
The PRN class that handles the print calls:
class PRN:
@staticmethod
def cyan(p_str):
"""print some text with cyan foreground"""
if os.name == 'nt':
# we'll try the Colorama option but if it fails we can
# change the global variable for colours.
if coloursOn:
sys.stdout.write(Fore.CYAN + p_str + Fore.RESET)
else:
sys.stdout.write(p_str)
else:
# try Deez1.clrs for posix environment
sys.stdout.write(clrs.cyan + p_str + clrs.ENDC)
If colorama doesn't work on a Windows system for some reason I can change the global boolean coloursOn
.
Is this an incredibly klutzy/dumb implementation? From what I've read, so far, cross platform capability for ANSI color printing has only gotten shakier, not simpler.
colorsOn
for the sake of consistency. Using both spellings is liable to create a typo. \$\endgroup\$python
there's no need for it in the title? Apologies for the lack of initial capitals - I'm anti-capitalism but I'll try to refrain from that when discussing code. \$\endgroup\$