Python цветной вывод в консоль windows

В Python 3 для вывода цветного текста в консоль можно использовать библиотеки colorama и termcolor. Так же можно изменять цвет с помощью ANSI - кодов без использования библиотек.

Python обладает достаточным количеством инструментов, чтобы выводить текст в консоль в любом цвете. Такой вывод не требует особых навыков, реализуется в несколько строк кода и используется как для выделения важной информации, так и для придания красоты тексту.

Сделать текст цветным можно двумя способами: использовать встроенные средства языка или библиотеки. Каждый способ имеет плюсы и минусы, также существуют нюансы, касающиеся изменения цвета текста в консоли Windows.

C помощью встроенных средств языка

В Python можно форматировать текст с помощью ANSI кодов. Это очень мощный и удобный инструмент, с его помощью программист может напрямую определять цвет текста.

ANSI коды работают на большинстве дистрибутивов Linux, но не поддерживаются консолью операционной системы Windows до Windows 10. В статье есть отдельный пункт про то, как запускать на Windows!

На разных дистрибутивах Linux и в Windows 10 цвет текста, созданный при помощи одного и того же ANSI кода, может отличаться. Это зависит от настроек консоли, её кастомизации пользователем и некоторых других факторов.

Изменять цвет текста с помощью ANSI кодов можно разными способами, например, использоваться функции или даже написать свой класс-обёртку для ANSI.

Использовать ANSI коды просто, для этого нужно знать базовый синтаксис и сами коды. Разбор на примере кода «33[31m33[43m»:

  • /033 — обозначение того, что дальше идет какой-то управляющий цветом код;
  • [31m — цвет текста (красный);
  • [43m — цвет фона (жёлтый).

После вывода этого в консоль, далее выводимая информация будет красного цвета на жёлтом фоне. Сбросить к начальным значениям : 33[0m.

Базовые коды:

  • 33[0-7m — это различные эффекты, такие как подчеркивание, мигание, жирность и так далее;
  • 33[30-37m — коды, определяющие цвет текста (черный, красный, зелёный, жёлтый, синий, фиолетовый, сине-голубой, серый);
  • 33[40-47m — коды, определяющие цвет фона.

Цвета

Цвет Текст Фон
Чёрный 30 40
Красный 31 41
Зелёный 32 42
Жёлтый 33 43
Синий 34 44
Фиолетовый 35 45
Бирюзовый 36 46
Белый 37 47

Эффекты

Код Значение
0 Сброс к начальным значениям
1 Жирный
2 Блёклый
3 Курсив
4 Подчёркнутый
5 Редкое мигание
6 Частое мигание
7 Смена цвета фона с цветом текста

Функции для вызова

Быстро покрасить строку в нужный цвет можно с помощью функций. Им нужно дать говорящие имена, передать в качестве аргумента строку и использовать в их теле правильный ANSI код.

Подход удобен тем, что можно объявить N функций, которые форматируют любой текст в нужный цвет и использовать их во всех своих программах, достаточно лишь импортировать модуль.

Например, так:

Код:

def out_red(text):
    print("33[31m {}" .format(text))
def out_yellow(text):
    print("33[33m {}" .format(text))
def out_blue(text):
    print("33[34m {}" .format(text))
out_red("Вывод красным цветом")
out_yellow("Текст жёлтого цвета")
out_blue("Синий текст")

Результат:

Мы меняли только цвет текста, но можно менять и цвет фона, добавлять дополнительные стили. Например, чтобы вывести подчёркнутый текст белого цвета на синем фоне, нужно написать так:

print("33[4m33[37m33[44m{}33[0m".format("Python 3"))

Вот так будет выглядеть вывод:

Обратите внимание на строку print("33[4m33[37m33[44m{}33[0m".format("Python 3")).

Здесь мы вывод осуществляли следующим образом:

  • 33[4m — подчёркнутый;
  • 33[37m — белая надпись;
  • 33[44m — синий фон;
  • {} — заменится на «Python 3»;
  • 33[0m — сброс к начальным значениям.

Как вывести цветной текст в консоль на Windows

В Linux по умолчанию встроена поддержка ANSI кодов консолью, а в Windows — нет. Это объясняется тем, что для линукса консоль является основным рабочим инструментом. В Windows консоль используется редко, поэтому нет смысла встраивать в неё подобные вещи.

Однако в Windows 10, начиная с версии Threshold 2, разработчики добавили в консоль поддержку управляющих кодов. Однако из-за того, что далеко не все пользуются новой ОС, писать консольные приложения с цветным текстом все ещё приходится с помощью дополнительных библиотек.

Так библиотека colorama поддерживает работу с Windows 10! Поэтому рекомендуется её использование.

Для того, чтобы код, написанный с помощью внутренних средств Python 3 или с помощью библиотеки termcolor заработал в Windows 10, надо включить поддержку ANSI для stdout в запущенной консоле.

Сделать это можно следующим образом:

import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

Вывод цветного текста в консоль с colorama

Colorama — самая популярная библиотека для вывода цветного текста на Python 3. Colorama позволяет использовать ANSI коды не только в Linux, но и в Windows.

Использование функций и методов библиотеки упрощает написание кода и делает более простым для поддержки. Больше не нужно запоминать или копировать ANSI коды. Команды настолько просты и интуитивно понятны, что с задачей справиться даже обычный пользователь.

Использование сторонней библиотеки, такой как colorama, не приводит к каким-то негативным эффектам. Перед использованием библиотеки colorama, её следует установить с помощью команды в консоле pip install colorama.

Приведём пример использования colorama:

import colorama
from colorama import Fore, Back, Style
colorama.init()
print(Fore.RED + 'Красный текст')
print(Back.BLUE + 'Синий фон')
print(Style.RESET_ALL)
print('Снова обычный текст')

Здесь мы импортировали модули для работы с текстом и фоном. И так же как и раньше мы выводили всё встроенными средствами Python, вывели всё в консоль.

Стоит обратить внимание на функцию init. Если её забыть запустить, то не будет поддерживаться вывод на Windows 10.

Только теперь нам не надо писать 33[44m, а достаточно написать Fore.BLUE, что конечно же удобно. Style.RESET_ALL — это сброс цветов консоли к начальным значениям.

Результат:

Цветной текст с помощью termcolor

Эта библиотека даёт программисту исчерпывающий инструментарий для работы с цветом текста.

Часто termcolor используют вместе с colorama. Termcolor используют непосредственно для написания кода, действительно, её синтаксис более удобный и простой.

Для установки библиотеки termcolor следует выполнить в консоле команду pip install termcolor.

Пример:

from termcolor import colored, cprint
print(colored('Привет мир!', 'red', attrs=['underline']))
print('Привет, я люблю тебя!')
cprint('Вывод с помощью cprint', 'green', 'on_blue')

Здесь мы воспользовались функциями colored и cprint. Первая позволяет создать строку для последующего вывода с необходимыми параметрами цветов и эффектов. Вторая сразу производит вывод в консоль.

Результат:

Заключение

Если мы делаем пару функций для вывода в консоль цветных сообщений об ошибках и предупреждениях, то можно их сделать и не подключая библиотек. Правда при подключении библиотеки код более читаемым становится.

При выборе между библиотеками colorama и termcolor, я бы остановился бы на colorama. Не только исходя из её большей популярности, но и из-за того, что она поддерживает работу с командной строкой Windows 10. Хотя cprint удобная функция в termcolor.

Building on joeld’s answer, using https://pypi.python.org/pypi/lazyme
pip install -U lazyme:

from lazyme.string import color_print
>>> color_print('abc')
abc
>>> color_print('abc', color='pink')
abc
>>> color_print('abc', color='red')
abc
>>> color_print('abc', color='yellow')
abc
>>> color_print('abc', color='green')
abc
>>> color_print('abc', color='blue', underline=True)
abc
>>> color_print('abc', color='blue', underline=True, bold=True)
abc
>>> color_print('abc', color='pink', underline=True, bold=True)
abc

Screenshot:

Enter image description here


Some updates to the color_print with new formatters, e.g.:

>>> from lazyme.string import palette, highlighter, formatter
>>> from lazyme.string import color_print
>>> palette.keys() # Available colors.
['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
>>> highlighter.keys() # Available highlights.
['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
>>> formatter.keys() # Available formatter,
['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']

Note: italic, fast blinking, and strikethrough may not work on all terminals, and they don’t work on Mac and Ubuntu.

E.g.,

>>> color_print('foo bar', color='pink', highlight='white')
foo bar
>>> color_print('foo bar', color='pink', highlight='white', reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', bold=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
foo bar

Screenshot:

Enter image description here

Библиотека Colorama позволяет управляющим символам ANSI (используются для создания цветного текста в терминале и позиционирования курсора) работать под MS Windows.

Если вы считаете Colorama полезной, не забудьте поблагодарить ее авторов и сделать пожертвование. Спасибо!

Установка

pip install colorama
# или
conda install -c anaconda colorama

Описание

Управляющие символы ANSI давно используются для создания цветного текста и позиционирования курсора в терминале на Unix и Mac. Colorama делает возможным их использование на платформе Windows, оборачивая stdout, удаляя найденные ANSI-последовательности (которые будут выглядеть как тарабарщина при выводе) и преобразуя их в соответствующие вызовы win32 для изменения состояния командной строки. На других платформах Colorama ничего не меняет.

В результате мы получаем простой кроссплатформенный API для отображения цветного терминального текста из Python, а также следующий приятный побочный эффект: существующие приложения или библиотеки, использующие ANSI-последовательности для создания цветного вывода на Linux или Mac, теперь могут работать и на Windows, просто вызвав colorama.init().

Альтернативный подход заключается в установке ansi.sys на машины с Windows, что обеспечивает одинаковое поведение для всех приложений, работающих с командной строкой. Colorama предназначена для ситуаций, когда это не так просто (например, может быть, у вашего приложения нет программы установки).

Демо-скрипты в репозитории исходного кода библиотеки выводят небольшой цветной текст, используя последовательности ANSI. Сравните их работу в Gnome-terminal и в Windows Command-Prompt, где отображение осуществляется с помощью Colorama:

ANSI-последовательности на Ubuntu под gnome-terminal

ANSI-последовательности на Ubuntu под gnome-terminal
ANSI-последовательности на Windows, используя Colorama
Те же ANSI-последовательности на Windows, используя Colorama

Эти скриншоты показывают, что в Windows Colorama не поддерживает ANSI ‘dim text’ (тусклый текст); он выглядит так же, как и ‘normal text’.

Использование

Инициализация

Приложения должны инициализировать Colorama с помощью:

from colorama import init
init()

В Windows вызов init() отфильтрует управляющие ANSI-последовательности из любого текста, отправленного в stdout или stderr, и заменит их на эквивалентные вызовы Win32.

На других платформах вызов init() не имеет никакого эффекта (если только вы не укажете другие дополнительные возможности; см. раздел «Аргументы Init», ниже). По задумке разработчиков такое поведение позволяет приложениям вызывать init() безоговорочно на всех платформах, после чего вывод ANSI должен просто работать.

Чтобы прекратить использование Colorama до выхода из программы, просто вызовите deinit(). Данный метод вернет stdout и stderr к их исходным значениям, так что Colorama будет отключена. Чтобы возобновить ее работу, используйте reinit(); это выгоднее, чем повторный вызов init() (но делает то же самое).

Цветной вывод

Кроссплатформенное отображение цветного текста может быть упрощено за счет использования константных обозначений для управляющих последовательностей ANSI, предоставляемых библиотекой Colorama:

from colorama import init
init()
from colorama import Fore, Back, Style
print(Fore.GREEN + 'зеленый текст')
print(Back.YELLOW + 'на желтом фоне')
print(Style.BRIGHT + 'стал ярче' + Style.RESET_ALL)
print('обычный текст')

При этом вы также можете использовать ANSI-последовательности напрямую в своем коде:

print('33[31m' + 'красный текст')
print('33[39m') # сброс к цвету по умолчанию

Еще одним вариантом является применение Colorama в сочетании с существующими ANSI библиотеками, такими как Termcolor или Blessings. Такой подход настоятельно рекомендуется для чего-то большего, чем тривиальное выделение текста:

from colorama import init
from termcolor import colored

# используйте Colorama, чтобы Termcolor работал и в Windows
init()

# теперь вы можете применять Termcolor для вывода
# вашего цветного текста
print(colored('Termcolor and Colorama!', 'red', 'on_yellow'))

Доступны следующие константы форматирования:

// цвет текста
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
// цвет фона
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
// яркость текста и общий сброс
Style: DIM, NORMAL, BRIGHT, RESET_ALL

Style.RESET_ALL сбрасывает настройки цвета текста, фона и яркости. Colorama выполнит этот сброс автоматически при выходе из программы.

Позиционирование курсора

Библиотекой поддерживаются ANSI-коды для изменения положения курсора. Пример их генерации смотрите в demos/demo06.py.

Аргументы Init

init() принимает некоторые **kwargs для переопределения поведения по умолчанию.

init(autoreset=False):
Если вы постоянно осуществляете сброс указанных вами цветовых настроек после каждого вывода, init(autoreset=True) будет выполнять это по умолчанию:

from colorama import init, Fore
init(autoreset=True)
print(Fore.GREEN + 'зеленый текст')
print('автоматический возврат к обычному')

init(strip=None):
Передайте True или False, чтобы определить, должны ли коды ANSI удаляться при выводе. Поведение по умолчанию — удаление, если программа запущена на Windows или если вывод перенаправляется (не на tty).

init(convert=None):
Передайте True или False, чтобы определить, следует ли преобразовывать ANSI-коды в выводе в вызовы win32. По умолчанию Colorama будет их конвертировать, если вы работаете под Windows и вывод осуществляется на tty (терминал).

init(wrap=True):
В Windows Colorama заменяет sys.stdout и sys.stderr прокси-объектами, которые переопределяют метод .write() для выполнения своей работы. Если эта обертка вызывает у вас проблемы, то ее можно отключить, передав init(wrap=False). Поведение по умолчанию — обертывание, если autoreset, strip или convert равны True.

Когда обертка отключена, цветной вывод на платформах, отличных от Windows, будет продолжать работать как обычно. Для кроссплатформенного цветного отображения текста можно использовать AnsiToWin32 прокси, предоставляемый Colorama, напрямую:

import sys
from colorama import init, Fore, AnsiToWin32
init(wrap=False)
stream = AnsiToWin32(sys.stderr).stream

# Python 2
print >>stream, Fore.RED + 'красный текст отправлен в stderr'

# Python 3
print(Fore.RED + 'красный текст отправлен в stderr', file=stream)

Распознаваемые ANSI-последовательности

Последовательности ANSI обычно имеют вид:

ESC [ <параметр> ; <параметр> ... <команда>

Где <параметр> — целое число, а <команда> — один символ. В <команда> передается ноль или более параметров. Если параметры не представлены, это, как правило, синоним передачи одного нуля. В последовательности нет пробелов; они были добавлены здесь исключительно для удобства чтения.

Единственные ANSI-последовательности, которые Colorama преобразует в вызовы win32, это:

ESC [ 0 m     # сбросить все (цвета и яркость)
    ESC [ 1 m     # яркий
    ESC [ 2 m     # тусклый (выглядит так же, как обычная яркость)
    ESC [ 22 м    # нормальная яркость
    
    # FOREGROUND (цвет текста)
    ESC [ 30 м     # черный
    ESC [ 31 м     # красный
    ESC [ 32 м     # зеленый
    ESC [ 33 м     # желтый
    ESC [ 34 m     # синий
    ESC [ 35 m     # пурпурный
    ESC [ 36 m     # голубой
    ESC [ 37 m     # белый
    ESC [ 39 m     # сброс
    
    # ФОН
    ESC [ 40 m     # черный
    ESC [ 41 m     # красный
    ESC [ 42 м     # зеленый
    ESC [ 43 m     # желтый
    ESC [ 44 m     # синий
    ESC [ 45 m     # пурпурный
    ESC [ 46 m     # голубой
    ESC [ 47 m     # белый
    ESC [ 49 m     # сброс
    
    # позиционирование курсора
    ESC [ y;x H    # позиционирование курсора в позиции x, y (у направлена вниз)
    ESC [ y;x f    # позиционирование курсора в точке x, y
    ESC [ n A      # перемещение курсора на n строк вверх
    ESC [ n B      # перемещение курсора на n строк вниз
    ESC [ n C      # перемещение курсора на n символов вперед
    ESC [ n D      # перемещение курсора на n символов назад
    
    # очистить экран
    ESC [ режим J     # очистить экран
    
    # очистить строку
    ESC [ режим K     # очистить строку

Несколько числовых параметров команды ‘m’ могут быть объединены в одну последовательность:

ESC [ 36 ; 45 ; 1 m     # яркий голубой текст на пурпурном фоне

Все другие ANSI-последовательности вида ESC [ <параметр> ; <параметр> … <команда> молча удаляются из вывода в Windows.

Любые другие формы ANSI-последовательностей, такие как односимвольные коды или альтернативные начальные символы, не распознаются и не удаляются. Однако было бы здорово добавить их. Вы можете сообщить разработчикам, если это будет полезно для вас, через Issues на GitHub.

Текущий статус и известные проблемы

Лично я тестировал библиотеку только на Windows XP (CMD, Console2), Ubuntu (gnome-terminal, xterm) и OS X.

Некоторые предположительно правильные ANSI-последовательности не распознаются (см. подробности ниже), но, насколько мне известно, никто еще не жаловался на это. Загадка.

См. нерешенные проблемы и список пожеланий: https://github.com/tartley/colorama/issues

Если у вас что-то не работает или делает не то, что вы ожидали, авторы библиотеки будут рады услышать об этом в списке проблем, указанном выше, также они с удовольствием ждут и предоставляют доступ к коммиту любому, кто напишет один или, может, пару рабочих патчей.

На чтение 6 мин Просмотров 10.9к. Опубликовано 30.03.2021

В этой статье показано, как использовать цветной вывод в терминале на Python используя библиотеки и стандартные средства.

Содержание

  1. Введение
  2. ANSI Escape Sequences
  3. Схема 16 цветов в Python
  4. Цветной вывод в Colorama
  5. Схема 256 цветов в Python
  6. Заключение

Введение

Вернуть текст в том же цвете терминала — типично для приложений CLI. Всегда есть случаи, когда мы хотим выделить вывод для пользователя, например, предупреждение или сообщение об ошибке. В этих случаях цветовая передача может иметь значение.

ANSI Escape Sequences

Ваш TeleTypeWriter (TTY), или, скорее, ваш терминал, не только способен показывать вывод программы, он также может отображать движущийся курсор, окрашивать текст, очищать весь экран и многое другое, чем просто статический вывод.

Возможно, вы видели утилиты командной строки с красочным текстом и индикаторами выполнения. Как мы контролируем представление данных, которые мы выводим на терминал?

Мы используем ANSI Escape Sequences/Codes (sequences — последовательности). Это специальные строки, которые изменяют поведение терминала. Знакомым примером может служить символ n, представляющий собой новую последовательность строк. Ввод этого символа приведет к печати новой строки в выходных данных.

Текст окрашивается на вашем терминале на основе ANSI Escape Sequences. Эта статья посвящена ANSI Escape последовательностям, для того чтобы применить цветной вывод.

В терминалах широко используются две цветовые схемы:

  • 16 цветов (8 фоновых + 8 передних)
  • 256 цветов

Давайте начнем раскрашивать наши выходные данные с помощью опции 16 цветов.

Схема 16 цветов в Python

16-цветовая схема состоит из двух наборов по 8 цветов в каждом (8 фонов и 8 передних планов), и они могут быть отображены в терминале с помощью следующего синтаксиса:

16 colors syntax

Давайте проверим эту схему, напечатав цветной узор с красным жирным текстом и желтым фоном. Код стиля для представления полужирного текста равен 2. Цветовые коды для красного текста переднего плана-31 и 43 для желтого фона.

Итак, чтобы получить этот макет, пишем:

print('33[2;31;43m CHEESY')

Выполните приведенную выше команду в вашем интерпретаторе Python (или в файле).

Вы увидите следующий вывод:

16 colors - example1

Как видно, наш текст перетекает на следующую строчку. Нам нужна точка сброса, чтобы остановить печать цветов.

Это можно сделать, добавив 33[0;0m к строке следующим образом:

print('33[2;31;43m CHEESY 33[0;0m')

Код 33[0;0m представляет собой шаблон сброса, который возвращает терминал обратно в исходную цветовую схему.

Это обеспечит следующий результат:

16 colors - example1

Согласитесь, выглядит намного лучше!

Цветной вывод в Colorama

Colorama — это пакет Python, который предоставляет цветной вывод текста на Python. Он поддерживает только 16-цветовую схему. Модуль подготавливает Escape ANSI последовательности для получения цветного текста.

Давайте установим модуль с помощью pip:

Мы рекомендуем вам установить его в виртуальной среде.

После настройки давайте перейдем к печати цветного текста с помощью Colorama:

# colorama_demo.py 
from colorama import init, Fore, Back, Style 

# Initializes Colorama 
init(autoreset=True) 

print(Style.BRIGHT + Back.YELLOW + Fore.RED + "CHEESY")

Сначала я импортирую функции init, чтобы инициализировать модуль и установить autoreset в True, чтобы нам не пришлось сбрасывать его вручную, Fore (текстовый объект переднего плана), Back (фоновый объект) и Style (объект стиля). Каждый объект имеет свой собственный набор констант, которые могут быть вызваны в функции print.

Добавляя эти компоненты удобным для человека способом, Colorama преобразует значения, такие как YELLOW (жёлтый цвет) в 43, для фонового объекта Back, RED (красный) в 31 для переднего объекта Fore и так далее. Так я получаю последовательность ANSI, как и в прошлый раз, хотя нам не нужно знать коды самим — Colorama делает это за нас.

Шаблон сброса не требуется, так как я установил аргумент autoreset в значение True при инициализации экземпляра.

Вывод программы будет выглядеть так:

Colorama - example

Схема 256 цветов в Python

С развитием технологий 256-цветовая схема наиболее часто встречается в терминалах. Если вы используете ОС на базе Linux, вы можете проверить цветовую схему, поддерживаемую терминалом, введя следующую команду:

Если эта команда возвращает xterm-256color, то ваш терминал поддерживает максимум 256 цветов.

Интересно, что это за цвета? Вы все узнаете сразу после того, как поймете синтаксис 256-цветовой схемы. Работа с 256 цветами немного отличается от работы с 16-цветовой схемой:

256 colors - syntax

Существует заполнитель, чтобы определить, будет ли цвет применен к тексту или фону: 38;5; — для текста и 48;5; — для фона. Затем следует цветовой код в диапазоне от 0 до 255.

Основываясь на приведенном выше синтаксисе, давайте попробуем воссоздать логотип StackAbuse в Python с помощью последовательности Escape ANSI.

Логотип содержит бледно-серый фон (33[48;5;236m) со словами: Stack белого цвета (33[38;5;231m) и Abuse оранжевого цвета (33[38;5;208m). И конечно, код сброса должен быть встроен в строку.

Тем не менее, мы можем воссоздать логотип с помощью этой последовательности ANSI:

>>> print("33[48;5;236m33[38;5;231mStack 33[38;5;208mAbuse33[0;0m")

Вывод программы:

Stack Abuse Logo - in Color

Потрясающе! Какие еще цвета может печатать терминал? Давайте посмотрим, напечатав все 256 цветов, поддерживаемых терминалом:

# colorspep8.py
def colors_16(color_):
    return("33[2;{num}m {num} 33[0;0m".format(num=str(color_)))


def colors_256(color_):
    num1 = str(color_)
    num2 = str(color_).ljust(3, ' ')
    if color_ % 16 == 0:
        return(f"33[38;5;{num1}m {num2} 33[0;0mn")
    else:
        return(f"33[38;5;{num1}m {num2} 33[0;0m")

print("The 16 colors scheme is:")
print(' '.join([colors_16(x) for x in range(30, 38)]))
print("nThe 256 colors scheme is:")
print(' '.join([colors_256(x) for x in range(256)]))

Этот код содержит две функции, которые печатают переменную, которую вы передаете в них, в соответствующих последовательностях Escape ANSI. Как только я запущу скрипт и передам Х в определенном диапазоне, например (30,38] для 16-цветовой схемы или (0-255] для 256-цветовой схемы, он распечатает индексы в цветах при этих значениях.

Это позволит распечатать обе цветовые схемы в терминале:

Stack Abuse Logo - in Color

Это может быть очень полезно в качестве краткого руководства при создании утилит командной строки.

Заключение

В этом уроке я рассказал, как печатать цветные выходные данные для символов, которые мы отправляем в поток stdout. Я показал, как это сделать с помощью встроенных функций Python, а также как использовать библиотеку Colorama.

Ссылка на оригинал статьи: stackabuse.com/how-to-print-colored-text-in-python/

Latest Version

Supported Python versions

Build Status

Colorama

Makes ANSI escape character sequences (for producing colored terminal text and
cursor positioning) work under MS Windows.

PyPI for releases |
Github for source |
Colorama for enterprise on Tidelift

If you find Colorama useful, please Donate with Paypal to the authors. Thank you!

Installation

Tested on CPython 2.7, 3.7, 3.8, 3.9, 3.10 and 3.11 and PyPy 2.7 and 3.8.

No requirements other than the standard library.

pip install colorama
# or
conda install -c anaconda colorama

Description

ANSI escape character sequences have long been used to produce colored terminal
text and cursor positioning on Unix and Macs. Colorama makes this work on
Windows, too, by wrapping stdout, stripping ANSI sequences it finds (which
would appear as gobbledygook in the output), and converting them into the
appropriate win32 calls to modify the state of the terminal. On other platforms,
Colorama does nothing.

This has the upshot of providing a simple cross-platform API for printing
colored terminal text from Python, and has the happy side-effect that existing
applications or libraries which use ANSI sequences to produce colored output on
Linux or Macs can now also work on Windows, simply by calling
colorama.just_fix_windows_console() (since v0.4.6) or colorama.init()
(all versions, but may have other side-effects – see below).

An alternative approach is to install ansi.sys on Windows machines, which
provides the same behaviour for all applications running in terminals. Colorama
is intended for situations where that isn’t easy (e.g., maybe your app doesn’t
have an installer.)

Demo scripts in the source code repository print some colored text using
ANSI sequences. Compare their output under Gnome-terminal’s built in ANSI
handling, versus on Windows Command-Prompt using Colorama:

ANSI sequences on Ubuntu under gnome-terminal.

Same ANSI sequences on Windows, using Colorama.

These screenshots show that, on Windows, Colorama does not support ANSI ‘dim
text’; it looks the same as ‘normal text’.

Usage

Initialisation

If the only thing you want from Colorama is to get ANSI escapes to work on
Windows, then run:

from colorama import just_fix_windows_console
just_fix_windows_console()

If you’re on a recent version of Windows 10 or better, and your stdout/stderr
are pointing to a Windows console, then this will flip the magic configuration
switch to enable Windows’ built-in ANSI support.

If you’re on an older version of Windows, and your stdout/stderr are pointing to
a Windows console, then this will wrap sys.stdout and/or sys.stderr in a
magic file object that intercepts ANSI escape sequences and issues the
appropriate Win32 calls to emulate them.

In all other circumstances, it does nothing whatsoever. Basically the idea is
that this makes Windows act like Unix with respect to ANSI escape handling.

It’s safe to call this function multiple times. It’s safe to call this function
on non-Windows platforms, but it won’t do anything. It’s safe to call this
function when one or both of your stdout/stderr are redirected to a file – it
won’t do anything to those streams.

Alternatively, you can use the older interface with more features (but also more
potential footguns):

from colorama import init
init()

This does the same thing as just_fix_windows_console, except for the
following differences:

  • It’s not safe to call init multiple times; you can end up with multiple
    layers of wrapping and broken ANSI support.
  • Colorama will apply a heuristic to guess whether stdout/stderr support ANSI,
    and if it thinks they don’t, then it will wrap sys.stdout and
    sys.stderr in a magic file object that strips out ANSI escape sequences
    before printing them. This happens on all platforms, and can be convenient if
    you want to write your code to emit ANSI escape sequences unconditionally, and
    let Colorama decide whether they should actually be output. But note that
    Colorama’s heuristic is not particularly clever.
  • init also accepts explicit keyword args to enable/disable various
    functionality – see below.

To stop using Colorama before your program exits, simply call deinit().
This will restore stdout and stderr to their original values, so that
Colorama is disabled. To resume using Colorama again, call reinit(); it is
cheaper than calling init() again (but does the same thing).

Most users should depend on colorama >= 0.4.6, and use
just_fix_windows_console. The old init interface will be supported
indefinitely for backwards compatibility, but we don’t plan to fix any issues
with it, also for backwards compatibility.

Colored Output

Cross-platform printing of colored text can then be done using Colorama’s
constant shorthand for ANSI escape sequences. These are deliberately
rudimentary, see below.

from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')

…or simply by manually printing ANSI sequences from your own code:

print('33[31m' + 'some red text')
print('33[39m') # and reset to default color

…or, Colorama can be used in conjunction with existing ANSI libraries
such as the venerable Termcolor
the fabulous Blessings,
or the incredible _Rich.

If you wish Colorama’s Fore, Back and Style constants were more capable,
then consider using one of the above highly capable libraries to generate
colors, etc, and use Colorama just for its primary purpose: to convert
those ANSI sequences to also work on Windows:

SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama.
We are only interested in converting ANSI codes to win32 API calls, not
shortcuts like the above to generate ANSI characters.

from colorama import just_fix_windows_console
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
just_fix_windows_console()

# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))

Available formatting constants are:

Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Style: DIM, NORMAL, BRIGHT, RESET_ALL

Style.RESET_ALL resets foreground, background, and brightness. Colorama will
perform this reset automatically on program exit.

These are fairly well supported, but not part of the standard:

Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX

Cursor Positioning

ANSI codes to reposition the cursor are supported. See demos/demo06.py for
an example of how to generate them.

Init Keyword Args

init() accepts some **kwargs to override default behaviour.

init(autoreset=False):

If you find yourself repeatedly sending reset sequences to turn off color
changes at the end of every print, then init(autoreset=True) will
automate that:

from colorama import init
init(autoreset=True)
print(Fore.RED + 'some red text')
print('automatically back to default color again')
init(strip=None):
Pass True or False to override whether ANSI codes should be
stripped from the output. The default behaviour is to strip if on Windows
or if output is redirected (not a tty).
init(convert=None):
Pass True or False to override whether to convert ANSI codes in the
output into win32 calls. The default behaviour is to convert if on Windows
and output is to a tty (terminal).
init(wrap=True):

On Windows, Colorama works by replacing sys.stdout and sys.stderr
with proxy objects, which override the .write() method to do their work.
If this wrapping causes you problems, then this can be disabled by passing
init(wrap=False). The default behaviour is to wrap if autoreset or
strip or convert are True.

When wrapping is disabled, colored printing on non-Windows platforms will
continue to work as normal. To do cross-platform colored output, you can
use Colorama’s AnsiToWin32 proxy directly:

import sys
from colorama import init, AnsiToWin32
init(wrap=False)
stream = AnsiToWin32(sys.stderr).stream

# Python 2
print >>stream, Fore.BLUE + 'blue text on stderr'

# Python 3
print(Fore.BLUE + 'blue text on stderr', file=stream)

Recognised ANSI Sequences

ANSI sequences generally take the form:

ESC [ <param> ; <param> ... <command>

Where <param> is an integer, and <command> is a single letter. Zero or
more params are passed to a <command>. If no params are passed, it is
generally synonymous with passing a single zero. No spaces exist in the
sequence; they have been inserted here simply to read more easily.

The only ANSI sequences that Colorama converts into win32 calls are:

ESC [ 0 m       # reset all (colors and brightness)
ESC [ 1 m       # bright
ESC [ 2 m       # dim (looks same as normal brightness)
ESC [ 22 m      # normal brightness

# FOREGROUND:
ESC [ 30 m      # black
ESC [ 31 m      # red
ESC [ 32 m      # green
ESC [ 33 m      # yellow
ESC [ 34 m      # blue
ESC [ 35 m      # magenta
ESC [ 36 m      # cyan
ESC [ 37 m      # white
ESC [ 39 m      # reset

# BACKGROUND
ESC [ 40 m      # black
ESC [ 41 m      # red
ESC [ 42 m      # green
ESC [ 43 m      # yellow
ESC [ 44 m      # blue
ESC [ 45 m      # magenta
ESC [ 46 m      # cyan
ESC [ 47 m      # white
ESC [ 49 m      # reset

# cursor positioning
ESC [ y;x H     # position cursor at x across, y down
ESC [ y;x f     # position cursor at x across, y down
ESC [ n A       # move cursor n lines up
ESC [ n B       # move cursor n lines down
ESC [ n C       # move cursor n characters forward
ESC [ n D       # move cursor n characters backward

# clear the screen
ESC [ mode J    # clear the screen

# clear the line
ESC [ mode K    # clear the line

Multiple numeric params to the 'm' command can be combined into a single
sequence:

ESC [ 36 ; 45 ; 1 m     # bright cyan text on magenta background

All other ANSI sequences of the form ESC [ <param> ; <param> ... <command>
are silently stripped from the output on Windows.

Any other form of ANSI sequence, such as single-character codes or alternative
initial characters, are not recognised or stripped. It would be cool to add
them though. Let me know if it would be useful for you, via the Issues on
GitHub.

Status & Known Problems

I’ve personally only tested it on Windows XP (CMD, Console2), Ubuntu
(gnome-terminal, xterm), and OS X.

Some valid ANSI sequences aren’t recognised.

If you’re hacking on the code, see README-hacking.md. ESPECIALLY, see the
explanation there of why we do not want PRs that allow Colorama to generate new
types of ANSI codes.

See outstanding issues and wish-list:
https://github.com/tartley/colorama/issues

If anything doesn’t work for you, or doesn’t do what you expected or hoped for,
I’d love to hear about it on that issues list, would be delighted by patches,
and would be happy to grant commit access to anyone who submits a working patch
or two.

License

Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see
LICENSE file.

Professional support

Tidelift Professional support for colorama is available as part of the
Tidelift Subscription.
Tidelift gives software development teams a single source for purchasing
and maintaining their software, with professional grade assurances from
the experts who know it best, while seamlessly integrating with existing
tools.

Thanks

See the CHANGELOG for more thanks!

  • Marc Schlaich (schlamar) for a setup.py fix for Python2.5.
  • Marc Abramowitz, reported & fixed a crash on exit with closed stdout,
    providing a solution to issue #7’s setuptools/distutils debate,
    and other fixes.
  • User ‘eryksun’, for guidance on correctly instantiating ctypes.windll.
  • Matthew McCormick for politely pointing out a longstanding crash on non-Win.
  • Ben Hoyt, for a magnificent fix under 64-bit Windows.
  • Jesse at Empty Square for submitting a fix for examples in the README.
  • User ‘jamessp’, an observant documentation fix for cursor positioning.
  • User ‘vaal1239’, Dave Mckee & Lackner Kristof for a tiny but much-needed Win7
    fix.
  • Julien Stuyck, for wisely suggesting Python3 compatible updates to README.
  • Daniel Griffith for multiple fabulous patches.
  • Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty
    output.
  • Roger Binns, for many suggestions, valuable feedback, & bug reports.
  • Tim Golden for thought and much appreciated feedback on the initial idea.
  • User ‘Zearin’ for updates to the README file.
  • John Szakmeister for adding support for light colors
  • Charles Merriam for adding documentation to demos
  • Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes
  • Florian Bruhin for a fix when stdout or stderr are None
  • Thomas Weininger for fixing ValueError on Windows
  • Remi Rampin for better Github integration and fixes to the README file
  • Simeon Visser for closing a file handle using ‘with’ and updating classifiers
    to include Python 3.3 and 3.4
  • Andy Neff for fixing RESET of LIGHT_EX colors.
  • Jonathan Hartley for the initial idea and implementation.

Introduction

It’s typical for CLI apps to return text in the same color of the terminal. There are always cases when we want to highlight output to the user, for example, a warning or error message. In those cases, a dash of color could make a difference.

This article shows you how to print colored output in the terminal in Python with and without libraries.

ANSI Escape Sequences

Your Teletypewriter (TTY), or rather your terminal, is not only capable of showing the output of a program. It can display a moving cursor, color the text, clear the entire screen, and much more than just static output. You may have seen command-line utilities with colorful text and progress bars. How do we control the presentation of the data we’re are outputting to the terminal?

We use ANSI Escape Sequences/Codes. These are special strings that modify the behavior of the terminal. A familiar example would be the n character, which is a New Line sequence. Entering this character will print a new line in the output.

The text is colored on your terminal based on ANSI Escape sequences. This article focuses on the escape sequences to color text.

Two color schemes are widely used in the terminals:

  • 16 colors (8 Background + 8 Foreground)
  • 256 colors

Let’s begin coloring our output with the 16 color option.

16 Colors in Raw Python

The 16 colors scheme comprises two sets of 8 colors each (8 backgrounds and 8 foregrounds) and they can be displayed in the terminal by using the following syntax:

Let’s put this to the test, by printing a cheesy color pattern with a red bold text and yellow background. The style code to represent bold text is 2. The color codes for the foreground red text is 31 and 43 for the yellow background. So, with that in mind, the syntax for representing this layout is:

print('33[2;31;43m CHEESY')

Run the above command in your Python interpreter (or a file). You will see this output:

That’s not quite right, our cheesy text is spilling over to the next line. We need a reset point to stop the printing of colors. This can be done by appending 33[0;0m to the string as:

print('33[2;31;43m CHEESY 33[0;0m')

The 33[0;0m code represents a reset pattern that returns the terminal back to its original color scheme. This will provide the following output:

Looks much better.

16 Colors In Colorama — A Built-in Module

Colorama is a Python package that provides methods to print colored text in Python. It only supports the 16-colors scheme. The module prepares the ANSI Escape sequences to produce the colored text. Let’s install the module with pip:

$ pip install colorama

We recommend you install it within a virtual environment. Once set up, let’s get to printing colored text with Colorama:

# colorama_demo.py
from colorama import init, Fore, Back, Style

# Initializes Colorama
init(autoreset=True)

print(Style.BRIGHT + Back.YELLOW + Fore.RED + "CHEESY")

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

We first import the functions: init() (to initialize the module and to set the autoreset to True so we don’t have to reset it manually), Fore (Foreground text object), Back (Background Object) and Style (Style Object). Each object has its own set of constants that can be called in the print() function.

By appending these components in a human-friendly way, Colorama converts values like YELLOW to 43, for the Back object, RED to 31 for the Fore object, etc. Under the hood, we end up with an ANSI Sequence, just like last time, though, we don’t have to know the codes ourselves — Colorama does this for us.

No reset pattern is required, since we’ve set the autoreset argument to True while initializing the instance.

Running the code will display this:

256 Colors in Raw Python

With the advancement in technologies, the 256-color scheme is the most commonly found in terminals. If you are on a Linux based OS, you can check your terminal-supported color scheme by entering the following command:

$ echo $TERM

If this command returns xterm-256color, then your terminal supports a maximum of 256 colors.

Wondering what those colors are?

We can dive in right after we understand the syntax of a 256-color scheme. Working with 256 colors is a bit different than working with the 16-color scheme:

There’s a placeholder to determine whether the color will be applied to the text or the background; 38;5; is for the text and 48;5; is for the background. This is followed by the color code ranging from 0 to 255.

Based on the above syntax, let’s try recreating the StackAbuse logo in Python using an ANSI Escape Sequence.

The logo contains a pale grey background (33[48;5;236m) with the words: Stack in white (33[38;5;231m) and Abuse in orange (33[38;5;208m). And of course, the reset code needs to be embedded in the string.

That being said, we can recreate the logo with this ANSI Sequence:

>>> print("33[48;5;236m33[38;5;231mStack 33[38;5;208mAbuse33[0;0m")

This results in:

Awesome! What other colors can the terminal print? Let’s take a look, by printing all the 256 colors supported by the terminal:

# colorspep8.py
def colors_16(color_):
    return("33[2;{num}m {num} 33[0;0m".format(num=str(color_)))


def colors_256(color_):
    num1 = str(color_)
    num2 = str(color_).ljust(3, ' ')
    if color_ % 16 == 0:
        return(f"33[38;5;{num1}m {num2} 33[0;0mn")
    else:
        return(f"33[38;5;{num1}m {num2} 33[0;0m")

print("The 16 colors scheme is:")
print(' '.join([colors_16(x) for x in range(30, 38)]))
print("nThe 256 colors scheme is:")
print(' '.join([colors_256(x) for x in range(256)]))

This script contains two functions that print the variable you pass into them, in the respective ANSI Escape Sequences. Once we run the script, and pass in x in a certain range, such as (30,38] for the 16-color scheme, or (0-255] for the 256-color scheme, it’ll print out the indices in the colors at those values.

This will print out both color-coded schemes in the terminal:

This can be very helpful as a quick reference while building command-line utilities.

Conclusion

In this tutorial, we’ve gone over how to print colored output, for the characters we send off to the stdout stream. We’ve explored how to do this using the built-in functionality Python offers, as well as how to use the Colorama library.

Is there a way we can print colors onto our console via Python? Yes, the most straightforward way is to use Python Colorama. macOS and Linux have their own inbuilt console color codes that do not work on Windows. This module makes sure those commands work on Windows and provides its own set of commands for console color settings.

What is Colorama?

Colorama is a Python module that displays colored output in consoles. Any text that is shown in the console can have its foreground and background changed.

macOS and Linux have their own inbuilt console color codes that do not work on Windows. This module makes sure those commands work on Windows as well.

You can check out Colorama public GitHub repo here.

Setting up Colorama

As of Python 3.10, this module is NOT a part of the Python Standard Library. To install manually, use PIP or Anaconda.

Running any of these commands will automatically install the latest version of colorama.

PIP Installation (Windows)
pip install colorama
PIP Installation (Linux)
sudo pip3 install colorama
Anaconda Installation
conda install -c anaconda colorama

After installation, you can import colorama into your Python Project.

Importing the Module
import colorama

[Fixed] Module Seaborn has no Attribute Histplot Error

How to use Python Colorama

Initializing Colorama

Our first step is to initialize Colorama by running the init() method, as follows:

import colorama
colorama.init()

init() can take some keyword arguments, here’s a rundown:

Keyword Argument + Default Value Description
init(autoreset = True) Setting this to True will reset color and style settings after each line.
init(strip = None) Setting this to True will remove ANSI codes from the output. The default behavior is to strip if on Windows or if the output is redirected.
init(convert = None) Passing True will convert ANSI codes in the output into win32 calls. The default behavior is to convert if on Windows, and output is to a terminal.
init(wrap = True) On Windows, Colorama works by replacing sys.stdout and sys.stderr with proxy objects, which override the .write() method to do their work. If this wrapping causes you problems, then this can be disabled by passing init(wrap=False). The default behavior is to wrap if auto-reset or strip or convert are True.

Writing Colored Text

The following program demonstrates how we can write colored text and background.

from colorama import init, Fore, Back
init()

# Fore changes the text's foreground color
print(Fore.BLUE + "Blue Letters")

#Back changes the text's background color
print(Back.WHITE + "White Background")

Output

blueText-whiteBackground

This provides us with blue text on a white background.

Available Console Colors

These are all the colors Colorama provides:

  • Fore.RED
  • Fore.GREEN
  • Fore.YELLOW
  • Fore.BLUE
  • Fore.MAGENTA
  • Fore.CYAN
  • Fore.WHITE

Applying Bold Style Settings

There are three text styles you can apply that effect text opacity.

  • DIM
  • NORMAL
  • BRIGHT
from colorama import init, Fore, Style
init()

# Prints text with minimum opacity 
print(Fore.BLUE + Style.DIM + "Blue Letters")

# Prints text with default console opacity
print(Fore.BLUE + Style.NORMAL + "Blue Letters")

# Prints text with high opacity (Bold letters)
print(Fore.BLUE + Style.BRIGHT + "Blue Letters")

Note: These settings may not be visible on all terminals.

Output

text-styles

Resetting the Color/Style Settings

You can reset all the colors and style settings by simply passing Style.RESET_ALL(). Running this method will reset everything back to default console settings.

from colorama import init, Fore, Back, Style
init()

print(Fore.BLUE +  Back.WHITE + "Sample Text" + Style.RESET_ALL)
print("Reset to default settings")

If you’re constantly going to be using different color settings, you can enable auto-reset upon initialization like this:

colorama.init(autoreset = True)

This resets to default settings after the execution of each line.

Output

sample-text-reset

Adjusting Console Font Size

This is unfortunately not possible. Python has no control over the size of the printed text. That’s entirely dependent on the settings of your terminal emulator.

The only way to print out large letters onto your console is to use ASCII Graphics.

Implementing Blinking Console Text

Here’s a way you add Blinking text using Colorama.

import colorama
colorama.init()

text=colored("HI THERE!", color="magenta", on_color="on_cyan", attrs=["blink"])
print(text)

Note that Windows terminals do not support blinking text.

Clearing Console Screen

Here’s an example for using the colorama to clear your output console screen.

import colorama
colorama.init()

print(cr.ansi.clear_screen())

Other Methods to Implement Console Color Formatting

Python termcolor

Termcolor is another module that allows similar color formatting for console outputs. It’s also an external module. You should install manually using PIP or Anaconda.

import colorama
from termcolor import colored

colorama.init()

print(colored("red color", "red"))
print(colored("yellow color", "yellow"))
print(colored("blue color", "blue"))
print(colored("cyan color", "cyan"))
print(colored("green color", "green"))
print(colored("magenta color", "magenta"))

Output

Python termcolor colorama

Common Errors in Colorama

Requirement already satisfied: colorama in /usr/lib/python2.7/dist-packages.

Make sure your header code’s Python Version matches the one you’re currently Using.

If you’re using Python 2, your header code should look like this:

#!usr/bin/env python

Alternatives to Colorama

Here’s a rundown of alternatives to the colorama module. Links for their repos are also provided.

  • Python Fire
  • Gooey
  • click
  • python-prompt-toolkit

Python termcolor vs Python colorama

Despite both functions working in conjunction with each other, here are a few differences.

termcolor colorama
termcolor is a python module for ANSII Color formatting for output in the terminal.  Cross-platform printing of colored text can be done using’s constant shorthand for ANSI escape sequences.
Only provides color formatting for console display. Provides attributes that allow you to strip, convert and wrap ANSI codes.
It can be installed using PIP/Anaconda. Not part of the Standard Library It can be installed using PIP/Anaconda. Not part of the Standard Library

FAQs on Python Colorama

How to Install Colorama for Ubuntu?

Similar to Linux, running:
sudo -H python3 -m pip install colorama
will install colorama for Ubuntu OS

Conclusion

We have looked at how to implement Python Colorama to color format console outputs. An alternative to Colorama has been reviewed. Style settings to change the console text appearance have been evaluated. This is a must-use module if you’re working with results within your system console.

Trending Python Articles

  • [Fixed] Module Seaborn has no Attribute Histplot Error

    [Fixed] Module Seaborn has no Attribute Histplot Error

    January 18, 2023

  • Thonny: Text Wrapping Made Easy

    Thonny: Text Wrapping Made Easy

    by Rahul Kumar YadavJanuary 18, 2023

  • [Fixed] JavaScript error: IPython is Not Defined

    [Fixed] JavaScript error: IPython is Not Defined

    by Rahul Kumar YadavJanuary 18, 2023

  • [Fixed] “io.unsupportedoperation not readable” Error

    [Fixed] “io.unsupportedoperation not readable” Error

    by Rahul Kumar YadavJanuary 18, 2023

Понравилась статья? Поделить с друзьями:
  • Python скачать для windows 10 64 bit на русском торрент
  • Python скачать для windows 10 64 bit на русском официальный сайт
  • Python скачать для windows 10 64 bit portable
  • Python скачать для windows 10 64 bit intel
  • Python скачать бесплатно на русском языке для windows 10