Python colorama как пользоваться

Цветной вывод текста в Python

Всем привет сегодня я хотел рассказать вам «Как сделать цветной вывод текста в Python?» это даже может сделать не опытный человек не имея каких-то знаний. Поэтому если вам интересно то продолжайте читать и тогда все поймете.

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

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

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

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

  • «033[» — обозначение того, что дальше идет какой-то управляющий цветом код.
  • 37m — это код цвета а именно красный.
  • 43m — это код цвет фона для текста.

Именно через этот ANSI-код мы можем делать текст разноцветным, не забывайте ставить «» иначе будет ошибка.

Давайте сделаем вывод текста на консоле через функции.

def out_red(text): print("\033[34m<>".format(text)) out_red("ПРИВЕТ")

Через print() мы задали цвет текста «ПРИВЕТ» синим цветом. Также можно добавить фон и стиль текста все в одну строку.

print("\033[3m\033[33m\033[41m<>\033[0m".format("Htua_0111100000"))
  • \033[3m — отвечает за стилб текста в данном случае это курсив.
  • \033[33m — отвечает за цвет текста.
  • \033[41m — отвечает за цвет фона.
  • <> — заменит на «Htua_0111100000»
  • \033[0m — отвечает за сброс к начальным значениям.
Читайте также:  Поиск минимального значения массива java

Вобщем вот целая таблица с кодами цвета, фона и стилей.

Сброс к начальным значениям

Смена цвета фона с цветом текста

Цветной вывод текста в Python через библиотеку Colorama

Этой библиотекой тоже можно сделать цветной текст. Достаточно просто знать код и все. Для того чтобы начать работать нужно просто установить библиотеку pip install colorama потом можно начать работать с этой библиотекой. Создайте файл colorama.py и можно приступать к написанию кода.

from colorama import init, Fore from colorama import Back from colorama import Style init(autoreset=True) print(Fore.BLUE + 'some red text') print(Back.WHITE + 'and with a green background') print(Style.BRIGHT + 'and in dim text') print(Style.RESET_ALL) print('back to normal now')

Вывод текста через Colorama

  1. Cначала импортируем init, Back, Style то есть все необходимые нам функции для вывода текста на консоль.
  2. Стоит обратить внимание на функцию init . Если её забыть запустить, то не будет поддерживаться вывод на Windows 10.
  3. print(Fore.BLUE + ‘some red text’) — это задает цвет текста также вы можете поменять на красный (RED) или зеленный (GREEN) и т.д.
  4. print(Back.WHITE + ‘and with a green background’) — это задает фон текста
  5. print(Style.BRIGHT + ‘and in dim text’) — стиль текста
  6. print(Style.RESET_ALL) — сброс всех стилей
  7. print(‘back to normal now’) — обычный текст

Цветной текст через библиотеку termcolor

Это тоже вторая библиотека отвечающее за цвет фон и так далее. pip install termcolor

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

Импортируем colored и cprint, и пишем print(colored(‘Привет мир!’, ‘red’, attrs=[‘underline’])) тут вобще намного легче чем предыдущая attrs = [‘underline’] задает стиль текста. Следущее сpint(‘Вывод с помощью cprint’, ‘green’, ‘on_blue’) — это функция отвечает за цвет текста и фон. сpint(‘Ваш любимый текст’, ‘цвет текста’, ‘фон текста’)

Вывод

В общем, благодаря ANSI-кодом, библиотека colorama и termcolor можно создавать ваши любимые тексты, кстати можно с этой темой можно создавать мини викторины или что то другое. Я надеюсь на то что вам понравилось эта статья и надеюсь в будущем я продолжу писать все больше и больше статей на разные темы. Спасибо за внимание!

Источник

How to Use Colorama in Python

Many built-in modules and libraries exist in Python to print the colored text in the terminal. The Colorama is one of the built-in Python modules to display the text in different colors. It is used to make the code more readable. Three formatting options are available in this module for coloring text. These are Back, Fore and Style. The background or foreground color of the text and the style of the text can be changed by this module. Different uses of this module have been explained in this tutorial.

Python Colorama init() Function

The init() function is used to initialize the Colorama before using it in the script. It can be used without any argument or with an argument. Some keyword arguments can be used in the init() function which is described below.

Argument Name Description
Autoreset It is used to reset the color and style after each line when the value of this argument is set to True.
Strip It is used to remove the ANSI code from the output when the value of this argument is set to True.
Convert It is used to convert the ANSI code of the output when the value of this argument is set to True.
Wrap It is used to disable the overriding task when the value of this argument is set to False.

Terminal Colors

The following colors can be used by the Colorama as the background and font color of the terminal.

Style Settings

Three text styles are available in Colorama to change the thickness of the text. These are:

Different ways to set the background and font colors for the terminal text have been in the next part of this tutorial.

Example 1: Print Text with Background and Font Color

Create a Python file with the following script that shows the way to change the background and the font color using the Colorama module. The autoreset argument has been used in the init() function to reset the previous color and style after each line. At first, the background color is set to RED, and the font color is set to BLUE for the text, “Welcome to LinuxHint”. Next, the background color is set to GREEN for the text, ‘I like programming’.

#Import required modules
import colorama
from colorama import Fore , Back , Style

#Initialize colorama
colorama. init ( autoreset = True )

#Print text using background and font colors
print ( Back. RED + Fore. BLUE + «Welcome to LinuxHint» )
#Add newline
print ( )
#Print text using background color
print ( Back. GREEN + «I like programming» )

Output
The following output will appear after executing the above script. The output shows that the color setting for the first text data didn’t overwrite the color setting of the second text and the color setting has been applied separately for each text because autoreset argument is set True in the script.

Example 2: Print Text with Color and Style

Create a Python file with the following script to know the way of setting the style for the terminal text with the color. At first, the font color is set to CYAN for the text, ‘Welcome to Linuxhint’. Next, the background color is set to YELLOW, and the style is set to DIM for the text, ‘Learn Python. The Style.RESET_ALL property will reset all previous color and style settings. Next, the font color is set to RED and the text style is set to BRIGHT for the text, ‘Bright text’. In the same way, the style is set to NORMAL for the text, ‘Normal Text’ after resetting all previous color and style settings.

#Import required module
from colorama import Fore , Back , Style

#Print text using font color
print ( Fore. CYAN + ‘Welcome to Linuxhint’ )
#Print text using background color and DIM style
print ( Back. YELLOW + Style. DIM + ‘Learn Python’ , end = » )
#Reset all style
print ( Style. RESET_ALL )
#Print text using font color and BRIGHT style
print ( Fore. RED + Style. BRIGHT + ‘Bright Text’ , end = » )
#Print reset all style again
print ( Style. RESET_ALL )
#Print text without any color and normal style
print ( Style. NORMAL + ‘Normal Text’ )

Output
The following output will appear after executing the above script. The output shows that the font color of the first text has been applied in the second text because no reset task was done. But the color and style setting for the third and fourth text has been done separately for using Style.RESET_ALL property.

Example 3: Print Color Text Without Colorama

Many other modules exist in Python to set the color and style for the terminal text. The termcolor module is one of them. You have to install the module before using it in the script. Run the following command to install the termcolor module.

After installation, create a Python file with the following script to set the background color and font color by using the termcolor module. The font color will be set to RED and the background color will be set to CYAN for the text, ‘Colored text using Python’ after executing this script.

#Import necessary module
from termcolor import colored

#Initialize a text variable
text = «Colored text using Python»
#Print the text with font and background colors
print ( colored ( text , ‘red’ , ‘on_cyan’ ) )

Output
The following output will appear after executing the above script.

Example 4: Clear Terminal Screen

The terminal screen can be cleared by using ansi.clear.screen() function of Colorama module. Create a Python file with the following to clear the terminal screen by using the Colorama module.

#Import colorama
import colorama as cl

#Imitialalize colorama
cl. init ( )
#Clear the terminal screen
print ( cl. ansi . clear_screen ( ) )

Output
The following output will appear after executing the above script.

Conclusion

The output of the terminal can be made more attractive and understandable for the users by using the Colorama module of Python. Different ways of coloring the text background and setting the style and color of the font of the terminal have been shown in this tutorial by using colorama and another module. I hope the Python users will be able to apply color and style to the terminal text after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью