How do I print colored output to the terminal in Python?

前端 未结 7 1056
日久生厌
日久生厌 2020-12-04 17:55

Is there any python equivalent for perl\'s

print color \'red\';
print ;
print color \'reset\';

available in python?

<
7条回答
  •  青春惊慌失措
    2020-12-04 18:07

    There are a few libraries that help out here. For cmdline tools I sometimes use colorama.

    e.g.

    from colorama import init, Fore, Back, Style
    init()
    
    def cprint(msg, foreground = "black", background = "white"):
        fground = foreground.upper()
        bground = background.upper()
        style = getattr(Fore, fground) + getattr(Back, bground)
        print(style + msg + Style.RESET_ALL)
    
    cprint("colorful output, wohoo", "red", "black")
    

    But instead of using strings, you might want to use an enum and/or add a few checks. Not the prettiest solution, but works on osx/linux and windows and is easy to use.

    Other threads about this topic and cross-platform support: e.g. here.

提交回复
热议问题