在python终端中打印颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22886353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:53:27  来源:igfitidea点击:

Printing colors in python terminal

pythonterminal

提问by Ethan Bierlein

I'd like to make a program that prints colors in the python terminal but I don't know how. I've heard that you can use certain escape sequences to print text in color, but I'm not sure of this. How can I print a string in a specific color using the python terminal?

我想制作一个在 python 终端中打印颜色的程序,但我不知道如何。我听说您可以使用某些转义序列来打印彩色文本,但我不确定这一点。如何使用 python 终端以特定颜色打印字符串?

Side note: I run a version of Linux.

旁注:我运行一个版本的 Linux。

采纳答案by Liam McInroy

Try the termcolormodule.

试试这个termcolor模块。

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

See Print in terminal with colors using Python?

请参阅使用 Python 在终端中使用颜色打印?

Also, you could use ANSI codes:

此外,您可以使用 ANSI 代码:

class bcolors:
    HEADER = '3[95m'
    OKBLUE = '3[94m'
    OKGREEN = '3[92m'
    WARNING = '3[93m'
    FAIL = '3[91m'
    ENDC = '3[0m'

    def disable(self):
        self.HEADER = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

print(bcolors.WARNING + "Warning" + bcolors.ENDC)