How to print colored text in Python?

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

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

30条回答
  •  既然无缘
    2020-11-21 05:31

    Print a string that starts a color/style, then the string, then end the color/style change with '\x1b[0m':

    print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
    

    Get a table of format options for shell text with following code:

    def print_format_table():
        """
        prints table of formatted text format options
        """
        for style in range(8):
            for fg in range(30,38):
                s1 = ''
                for bg in range(40,48):
                    format = ';'.join([str(style), str(fg), str(bg)])
                    s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
                print(s1)
            print('\n')
    
    print_format_table()
    

    Light-on-dark example (complete)

    Dark-on-light example (partial)

    top part of output

提交回复
热议问题