目录
新建一个测试的文件 ColorTest,导入模块DefaultColor
Colorama是一个Python库,用于在控制台(终端)上输出彩色文本。它提供了一些方便的函数和类,用于在命令行界面中添加颜色和样式。
pip3 install -i https://mirrors.aliyun.com/pypi/simple/ ? colorama
import colorama
# Fore:文本前置颜色
# Back:文本背景颜色
from colorama import Fore, Back, init
#初始化,启动彩色文本
init(autoreset=True)
class Info:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "我的名字是 %s,年龄是 %d" % (self.name, self.age)
result1 = Info("张三", 18)
result2 = Info("李四", 25)
print("这是一个绿色文本:" + Fore.GREEN + str(result1))
print("这是一个红色背景:" + Back.RED + "-------背景区分-----")
print("这是一个红色文本:" + Fore.RED + str(result2))
终端的字符颜色是用转义序列控制的,是文本模式下的系统显示功能,和具体的语言无关。转义序列是以 ESC 开头,即用 \033 来完成(ESC的 ASCII 码用十进制表示是27,用八进制表示就是033
)。
class Color:
END = '\033[0m' # normal
BOLD = '\033[1m' # bold
RED = '\033[1;91m' # red
GREEN = '\033[1;92m' # green
ORANGE = '\033[1;93m' # orange
BLUE = '\033[1;94m' # blue
PURPLE = '\033[1;95m' # purple
UNDERLINE = '\033[4m' # underline
CYAN = '\033[1;96m' # cyan
GREY = '\033[1;97m' # gray
BR = '\033[1;97;41m' # background red
BG = '\033[1;97;42m' # background green
BY = '\033[1;97;43m' # background yellow
print(Color.BOLD + "hello python" + Color.END)
print(Color.RED + "hello python" + Color.END)
print(Color.GREEN + "hello python" + Color.END)
print(Color.ORANGE + "hello python" + Color.END)
print(Color.BLUE + "hello python" + Color.END)
print(Color.PURPLE + "hello python" + Color.END)
print(Color.UNDERLINE + "hello python" + Color.END)
print(Color.CYAN + "hello python" + Color.END)
print(Color.GREY + "hello python" + Color.END)
print(Color.BR + "hello python" + Color.END)
print(Color.BG + "hello python" + Color.END)
print(Color.BY + "hello python" + Color.END)
DefaultColor.py
class Color:
END = '\033[0m' # normal
BOLD = '\033[1m' # bold
RED = '\033[1;91m' # red
GREEN = '\033[1;92m' # green
ORANGE = '\033[1;93m' # orange
BLUE = '\033[1;94m' # blue
PURPLE = '\033[1;95m' # purple
UNDERLINE = '\033[4m' # underline
CYAN = '\033[1;96m' # cyan
GREY = '\033[1;97m' # gray
BR = '\033[1;97;41m' # background red
BG = '\033[1;97;42m' # background green
BY = '\033[1;97;43m' # background yellow
import DefaultColor
def sum_number():
total = 0
for i in range(1, 11):
total += i
return total
result = sum_number()
print("导入DefaultColor模块Color函数,显示黄色" + DefaultColor.Color.ORANGE + "黄颜色输出" + DefaultColor.Color.END)
print("1+2+3+......10的总和是:", DefaultColor.Color.RED + str(result) + DefaultColor.Color.END)
所以后续需要输出颜色的时候? 都可以在脚本文件里使用,调用颜色方法如下:
import DefaultColor DefaultColor.Color.RED + str(result) + DefaultColor.Color.END DefaultColor.Color.ORANGE + "字符串" + DefaultColor.Color.END