如何使用Python 3打印彩色输出?

时间:2016-09-13 15:04:48

标签: python-3.x printing colors

我有一个简单的印刷声明:

print('hello friends')

我希望终端输出为蓝色。我怎样才能用Python3实现这个目标?

13 个答案:

答案 0 :(得分:11)

这是我用来为Python 3脚本中的特定输出着色的一类。您可以导入该类并使用如下: from colorprint import ColorPrint as _ _.print_fail('Error occurred, quitting program')

import sys

# Colored printing functions for strings that use universal ANSI escape sequences.
# fail: bold red, pass: bold green, warn: bold yellow, 
# info: bold blue, bold: bold white

class ColorPrint:

    @staticmethod
    def print_fail(message, end = '\n'):
        sys.stderr.write('\x1b[1;31m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_pass(message, end = '\n'):
        sys.stdout.write('\x1b[1;32m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_warn(message, end = '\n'):
        sys.stderr.write('\x1b[1;33m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_info(message, end = '\n'):
        sys.stdout.write('\x1b[1;34m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_bold(message, end = '\n'):
        sys.stdout.write('\x1b[1;37m' + message.strip() + '\x1b[0m' + end)

答案 1 :(得分:8)

由于Python是在C语言中解释和运行的,因此无需模块即可设置颜色。

您可以为这样的颜色定义一个类:

class color:
   PURPLE = '\033[1;35;48m'
   CYAN = '\033[1;36;48m'
   BOLD = '\033[1;37;48m'
   BLUE = '\033[1;34;48m'
   GREEN = '\033[1;32;48m'
   YELLOW = '\033[1;33;48m'
   RED = '\033[1;31;48m'
   BLACK = '\033[1;30;48m'
   UNDERLINE = '\033[4;37;48m'
   END = '\033[1;37;0m'

编写代码时,您可以简单地编写:

打印(color.BLUE +“你好朋友” + color.END)

请注意,您选择的颜色必须像您的类定义一样大写,并且这些是我个人认为令人满意的颜色选择。有关颜色选择以及实际上还有背景选择的更多信息,请参见:https://gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a

这是用于C的代码,但是一旦您意识到代码的编写方式,便可以轻松地适应Python。

以蓝色为例,因为这就是您要显示的内容。

BLUE = '033[1;37;48m'

\ 033告诉Python中断并注意以下格式。

1表示代码为粗体。 (我更喜欢1到0,因为它会弹出更多。)

34是实际的颜色代码。它选择蓝色。

48m是背景色。 48m与控制台窗口的阴影相同,因此似乎没有背景。

答案 2 :(得分:7)

要在控制台中使用颜色,请参阅herehere

有专门用于此任务的模块,例如coloramacurses

答案 3 :(得分:7)

使用colorama非常简单,只需执行此操作:

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")

这是Python3 REPL中的运行结果:

并调用此方法重置颜色设置:

print(Style.RESET_ALL)

答案 4 :(得分:6)

将这些类放入 test.py 文件附近的 Color.py 文件中,然后运行 test.py 。 我已经在Ubuntu Server 16.04和Linux Mint 18.2上测试了这些类。除了GColor( RGB )之外,所有类都工作得非常好,它可以在图形终端(如Linux Mint终端)中使用。 另外,您可以像下面这样使用这些类:

print(Formatting.Italic + ANSI_Compatible.Color(12) + "This is a " + Formatting.Bold + "test" + Formatting.Reset_Bold +  "!" + ANSI_Compatible.END + Formatting.Reset)
print(Color.B_DarkGray + Color.F_LightBlue + "This is a " + Formatting.Bold + "test" + Formatting.Reset_Bold +  "!" + Base.END)

结果:

enter image description here

注意:它不适用于Windows!

文件 Color.py

class Base:
    # Foreground:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    # Formatting
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'    
    # End colored text
    END = '\033[0m'
    NC ='\x1b[0m' # No Color

class ANSI_Compatible:
    END = '\x1b[0m'
    # If Foreground is False that means color effect on Background
    def Color(ColorNo, Foreground=True): # 0 - 255
        FB_G = 38 # Effect on foreground
        if Foreground != True:
            FB_G = 48 # Effect on background
        return '\x1b[' + str(FB_G) + ';5;' + str(ColorNo) + 'm'

class Formatting:
    Bold = "\x1b[1m"
    Dim = "\x1b[2m"
    Italic = "\x1b[3m"
    Underlined = "\x1b[4m"
    Blink = "\x1b[5m"
    Reverse = "\x1b[7m"
    Hidden = "\x1b[8m"
    # Reset part
    Reset = "\x1b[0m"
    Reset_Bold = "\x1b[21m"
    Reset_Dim = "\x1b[22m"
    Reset_Italic = "\x1b[23m"
    Reset_Underlined = "\x1b[24"
    Reset_Blink = "\x1b[25m"
    Reset_Reverse = "\x1b[27m"
    Reset_Hidden = "\x1b[28m"

class GColor: # Gnome supported
    END = "\x1b[0m"
    # If Foreground is False that means color effect on Background
    def RGB(R, G, B, Foreground=True): # R: 0-255  ,  G: 0-255  ,  B: 0-255
        FB_G = 38 # Effect on foreground
        if Foreground != True:
            FB_G = 48 # Effect on background
        return "\x1b[" + str(FB_G) + ";2;" + str(R) + ";" + str(G) + ";" + str(B) + "m"

class Color:
    # Foreground
    F_Default = "\x1b[39m"
    F_Black = "\x1b[30m"
    F_Red = "\x1b[31m"
    F_Green = "\x1b[32m"
    F_Yellow = "\x1b[33m"
    F_Blue = "\x1b[34m"
    F_Magenta = "\x1b[35m"
    F_Cyan = "\x1b[36m"
    F_LightGray = "\x1b[37m"
    F_DarkGray = "\x1b[90m"
    F_LightRed = "\x1b[91m"
    F_LightGreen = "\x1b[92m"
    F_LightYellow = "\x1b[93m"
    F_LightBlue = "\x1b[94m"
    F_LightMagenta = "\x1b[95m"
    F_LightCyan = "\x1b[96m"
    F_White = "\x1b[97m"
    # Background
    B_Default = "\x1b[49m"
    B_Black = "\x1b[40m"
    B_Red = "\x1b[41m"
    B_Green = "\x1b[42m"
    B_Yellow = "\x1b[43m"
    B_Blue = "\x1b[44m"
    B_Magenta = "\x1b[45m"
    B_Cyan = "\x1b[46m"
    B_LightGray = "\x1b[47m"
    B_DarkGray = "\x1b[100m"
    B_LightRed = "\x1b[101m"
    B_LightGreen = "\x1b[102m"
    B_LightYellow = "\x1b[103m"
    B_LightBlue = "\x1b[104m"
    B_LightMagenta = "\x1b[105m"
    B_LightCyan = "\x1b[106m"
    B_White = "\x1b[107m"

然后

文件 test.py

from Color import *

if __name__ == '__main__':
    print("Base:")
    print(Base.FAIL,"This is a test!", Base.END)

    print("ANSI_Compatible:")
    print(ANSI_Compatible.Color(120),"This is a test!", ANSI_Compatible.END)

    print("Formatting:")
    print(Formatting.Bold,"This is a test!", Formatting.Reset)

    print("GColor:") # Gnome terminal supported
    print(GColor.RGB(204,100,145),"This is a test!", GColor.END)

    print("Color:")
    print(Color.F_Cyan,"This is a test!",Color.F_Default)

结果:

在Ubuntu Server 16.04上

Result on Ubuntu Server 16.04

在Linux Mint 18.2上

Result on Linux Mint 18.2

答案 5 :(得分:5)

我使用colors模块。克隆git存储库,运行setup.py,你很好。然后,您可以非常轻松地打印带有颜色的文本:

import colors
print(colors.red('this is red'))
print(colors.green('this is green'))

这适用于命令行,但可能需要进一步配置IDLE。

答案 6 :(得分:3)

这个答案来自早期的python2答案

  1. 安装termcolor模块。

    pip3 install termcolor

  2. 从termcolor导入彩色图书馆。

    from termcolor import colored

  3. 使用提供的方法,下面是一个例子。

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

答案 7 :(得分:3)

尝试这种方式,无需导入模块,只需使用定义为常量的颜色代码编号:

BLUE = '34m'
message = 'hello friends'


def display_colored_text(color, text):
    colored_text = f"\033[{color}{text}\033[00m"
    return colored_text

示例:

>>> print(display_colored_text(BLUE, message))
hello friends

答案 8 :(得分:2)

对于懒惰的人:

无需安装任何其他库,它与我所知道的每个终端都兼容。

分类方法:

首先做import config as cfg

clipped是数据框。

            #### HEADER: ####
            print('{0:<23} {1:>24} {2:>26} {3:>26} {4:>11} {5:>11}'.format('Road name','Classification','Function','Form of road','Length','Distance') )

            #### Now row by row: ####
            for index, row in clipped.iterrows():
                rdName      = self.colorize(row['name1'],cfg.Green)
                rdClass     = self.colorize(row['roadClassification'],cfg.LightYellow)
                rdFunction  = self.colorize(row['roadFunction'],cfg.Yellow)
                rdForm      = self.colorize(row['formOfWay'],cfg.LightBlue)
                rdLength    = self.colorize(row['length'],cfg.White)
                rdDistance  = self.colorize(row['distance'],cfg.LightCyan)
                print('{0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}'.format(rdName,rdClass,rdFunction,rdForm,rdLength,rdDistance) )

{0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}的含义:

0, 1, 2, 3, 4, 5->列,在这种情况下总共有6个

30, 35, 20->列的宽度(请注意,您必须添加\033[96m的长度-对于Python来说也是一个字符串),只需进行实验即可:)

>, <->对齐:右,左(也有=用来填充零)

config.py: 中的内容

#colors
ResetAll = "\033[0m"

Bold       = "\033[1m"
Dim        = "\033[2m"
Underlined = "\033[4m"
Blink      = "\033[5m"
Reverse    = "\033[7m"
Hidden     = "\033[8m"

ResetBold       = "\033[21m"
ResetDim        = "\033[22m"
ResetUnderlined = "\033[24m"
ResetBlink      = "\033[25m"
ResetReverse    = "\033[27m"
ResetHidden     = "\033[28m"

Default      = "\033[39m"
Black        = "\033[30m"
Red          = "\033[31m"
Green        = "\033[32m"
Yellow       = "\033[33m"
Blue         = "\033[34m"
Magenta      = "\033[35m"
Cyan         = "\033[36m"
LightGray    = "\033[37m"
DarkGray     = "\033[90m"
LightRed     = "\033[91m"
LightGreen   = "\033[92m"
LightYellow  = "\033[93m"
LightBlue    = "\033[94m"
LightMagenta = "\033[95m"
LightCyan    = "\033[96m"
White        = "\033[97m"

结果:

enter image description here

答案 9 :(得分:1)

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def colour_print(text,colour):
    if colour == 'OKBLUE':
        string = bcolors.OKBLUE + text + bcolors.ENDC
        print(string)
    elif colour == 'HEADER':
        string = bcolors.HEADER + text + bcolors.ENDC
        print(string)
    elif colour == 'OKCYAN':
        string = bcolors.OKCYAN + text + bcolors.ENDC
        print(string)
    elif colour == 'OKGREEN':
        string = bcolors.OKGREEN + text + bcolors.ENDC
        print(string)
    elif colour == 'WARNING':
        string = bcolors.WARNING + text + bcolors.ENDC
        print(string)
    elif colour == 'FAIL':
        string = bcolors.HEADER + text + bcolors.ENDC
        print(string)
    elif colour == 'BOLD':
        string = bcolors.BOLD + text + bcolors.ENDC
        print(string)
    elif colour == 'UNDERLINE':
        string = bcolors.UNDERLINE + text + bcolors.ENDC
        print(string)

复制上面的代码即可。 只需轻松调用它们

colour_print('Hello world','OKBLUE')
colour_print('easy one','OKCYAN')
colour_print('copy and paste','OKGREEN')
colour_print('done','OKBLUE')

希望能帮到你

答案 10 :(得分:0)

我想向您展示如何进行颜色编码。如果您想在下面玩的话,这里还有一个游戏。如果您愿意,请复制并粘贴,并确保每个人都过得愉快!另外,这是针对Python 3,而不是2。 (游戏)

   # The Color Game!
# Thank you for playing this game.
# Hope you enjoy and please do not copy it. Thank you!

import colorama
from colorama import Fore
score = 0

def Check_Answer(answer):
    if (answer == "no"):
        print('correct')
        return True
    else:
        print('wrong')

answer = input((Fore.RED + "This is green."))
if Check_Answer(answer) == True:
    score = score + 1
else:
    pass

answer = input((Fore.BLACK + "This is red."))
if Check_Answer(answer) == True:
    score = score + 1
else:
    pass

answer = input((Fore.BLUE + "This is black."))

if Check_Answer(answer) == True:
    score = score + 1
else:
    pass

print('Your Score is ', score)

现在进行颜色编码。它还带有您可以尝试的颜色列表。

# Here is how to color code in Python 3!
# Some featured color codes are : RED, BLUE, GREEN, YELLOW, OR WHITE. I don't think purple or pink are not out yet.
# Here is how to do it. (Example is down below!)

import colorama
from colorama import Fore
print(Fore.RED + "This is red..")

答案 11 :(得分:0)

# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS

fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"

def print_six(row, format):
    for col in range(6):
        color = row*6 + col + 4
        if color>=0:
            text = "{:3d}".format(color)
            print (format(text,color), end=" ")
        else:
            print("   ", end=" ")

for row in range(-1,42):
    print_six(row, fg)
    print("",end=" ")
    print_six(row, bg)
    print()

# Simple usage: print(fg("text", 160))

Text with altering foreground and background, colors 0..141 Text with altering foreground and background, colors 142..255

答案 12 :(得分:-1)

对于Windows,只需执行以下操作:

import os
os.system("color 01")
print('hello friends')

其中“ 01”表示背景为黑色,文本颜色为蓝色。进入“ CMD提示”,然后键入颜色帮助以获取颜色列表。

相关问题