Подтвердить что ты не робот

Как распечатать цветной вывод с помощью Python 3?

У меня простой оператор печати:

print('hello friends')

Я хотел бы, чтобы выход был синим в терминале. Как я могу выполнить это с помощью Python3?

4b9b3361

Ответ 1

С колорамой это очень просто, просто сделайте это:

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

И вот результат работы в Python3 REPL:

И вызовите это, чтобы сбросить настройки цвета:

print(Style.RESET_ALL)

Ответ 2

Здесь мой класс, который я использую для цветного вывода в сценариях 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)

Ответ 3

Поместите эти классы в файл 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)

Результат:

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 16.04

Result on Ubuntu Server 16.04

В Linux Mint 18.2

Result on Linux Mint 18.2

Ответ 5

Я использую модуль цветов. Клонируйте репозиторий git, запустите setup.py и все в порядке. Затем вы можете распечатать текст с цветами очень легко, как это:

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

Это работает в командной строке, но может потребоваться дополнительная настройка для IDLE.

Ответ 6

Попробуйте, таким образом, без модулей импорта, просто используйте цветовые кодовые номера, определенные как константы:

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

Ответ 7

Этот ответ, который я получил от предыдущих ответов python2, которые

  1. Установите модуль терминов.

    pip3 install termcolor

  2. Импортируйте цветную библиотеку из termcolor.

    from termcolor import colored

  3. Используйте приведенные методы, приведенный ниже.

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

Ответ 8

# 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

Ответ 9

Я хотел бы показать вам, как цветовым кодом. Существует также игра, если вы хотите воспроизвести ее ниже. Скопируйте и вставьте, если хотите, и убедитесь, что у вас хороший день! Кроме того, это для Python 3, а не 2. (Game)

   # 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..")

Ответ 10

Для окон просто сделайте это:

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

Где написано "01", то есть фон черный, а цвет текста синий. Перейдите в CMD Prompt и введите справку по цвету для получения списка цветов.