How to print colored text in Python?

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

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

30条回答
  •  北海茫月
    2020-11-21 05:26

    My favorite way is with the Blessings library (full disclosure: I wrote it). For example:

    from blessings import Terminal
    
    t = Terminal()
    print t.red('This is red.')
    print t.bold_bright_red_on_black('Bright red on black')
    

    To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in nose-progressive:

    print t.on_green(' ')
    

    You can print in specific locations as well:

    with t.location(0, 5):
        print t.on_yellow(' ')
    

    If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python's standard string formatting to keep it readable:

    print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)
    

    The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!

提交回复
热议问题