How to print colored text in Python?

前端 未结 30 2907
谎友^
谎友^ 2020-11-21 04:41

How can I output colored text to the terminal in Python?

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 05:12

    Building on @joeld answer, using https://pypi.python.org/pypi/lazyme pip install -U lazyme :

    from lazyme.string import color_print
    >>> color_print('abc')
    abc
    >>> color_print('abc', color='pink')
    abc
    >>> color_print('abc', color='red')
    abc
    >>> color_print('abc', color='yellow')
    abc
    >>> color_print('abc', color='green')
    abc
    >>> color_print('abc', color='blue', underline=True)
    abc
    >>> color_print('abc', color='blue', underline=True, bold=True)
    abc
    >>> color_print('abc', color='pink', underline=True, bold=True)
    abc
    

    Screenshot:


    Some updates to the color_print with new formatters, e.g.:

    >>> from lazyme.string import palette, highlighter, formatter
    >>> from lazyme.string import color_print
    >>> palette.keys() # Available colors.
    ['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
    >>> highlighter.keys() # Available highlights.
    ['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
    >>> formatter.keys() # Available formatter, 
    ['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']
    

    Note: italic, fast blinking and strikethrough may not work on all terminals, doesn't work on Mac / Ubuntu.

    E.g.

    >>> color_print('foo bar', color='pink', highlight='white')
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', reverse=True)
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', bold=True)
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', faint=True)
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
    foo bar
    >>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
    foo bar
    

    Screenshot:

提交回复
热议问题