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

jav*_*ira 18 printing colors python-3.x

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

print('hello friends')
Run Code Online (Sandbox Code Playgroud)

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

Yuc*_*ong 14

使用colorama非常简单,只需这样做:

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")
Run Code Online (Sandbox Code Playgroud)

这是Python3 REPL中的运行结果:

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

print(Style.RESET_ALL)
Run Code Online (Sandbox Code Playgroud)


Nic*_*mel 13

这是我用来为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)
Run Code Online (Sandbox Code Playgroud)


小智 13

由于 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'
Run Code Online (Sandbox Code Playgroud)

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

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

请注意,您选择的颜色必须像您的类定义一样大写,而且这些是我个人认为令人满意的颜色选择。有关更全面的颜色选择以及背景选择,请参阅:https : //gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a

这是 C 的代码,但是一旦您了解代码的编写方式,就可以轻松地将其改编为 Python。

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

BLUE = '033[1;37;48m'
Run Code Online (Sandbox Code Playgroud)

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

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

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

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


Sae*_*odi 11

把这些类为Color.py文件靠近你test.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)
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明

注意:在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"
Run Code Online (Sandbox Code Playgroud)

和,

文件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)
Run Code Online (Sandbox Code Playgroud)

结果:

在Ubuntu Server 16.04上

在Ubuntu Server 16.04上的结果

在Linux Mint 18.2上

Linux Mint 18.2上的结果


And*_*kha 9

# 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))
Run Code Online (Sandbox Code Playgroud)

具有改变前景和背景的文本,颜色 0..141 具有改变前景和背景的文本,颜色 142..255


Rem*_*y J 7

要在控制台中使用颜色,请在此处此处查看.

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


小智 7

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

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


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

例子:

>>> print(display_colored_text(BLUE, message))
hello friends
Run Code Online (Sandbox Code Playgroud)


jat*_*h03 6

我使用颜色模块。克隆git存储库,运行setup.py,您就很好了。然后,您可以像这样很容易地打印带有颜色的文本:

import colors
print(colors.red('this is red'))
print(colors.green('this is green'))
Run Code Online (Sandbox Code Playgroud)

这在命令行上有效,但可能需要对IDLE进行进一步配置。