python colorama_Python colorama 模块 使用 说明

1 Colorama 模块说明

在上篇博客我们了解了prettytable的使用, 如下:

https://www.cndba.cn/cndba/dave/article/3564

使用prettytable模块之后,输出的内容格式看上去会非常整齐,但如果我们想要对部分内容重点显示,那么可以使用两种方法:

1)直接使用Python控制输出颜色

2)使用colorama模块

Colorama是一个python专门用来在控制台、命令行输出彩色文字的模块,可以跨平台使用。Pypi官方地址:https://www.cndba.cn/cndba/dave/article/3564

https://pypi.python.org/pypi/coloramahttps://www.cndba.cn/cndba/dave/article/3564

安装colorama模块

pip install colorama

可用格式常数:

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_ALLhttps://www.cndba.cn/cndba/dave/article/3564

其中:https://www.cndba.cn/cndba/dave/article/3564

Fore是针对字体颜色,Back是针对字体背景颜色,Style是针对字体格式

Colorma在使用时需要及时关闭colorma的作用范围,否则后面所有的输出都会是指定的颜色:https://www.cndba.cn/cndba/dave/article/3564

print(Style.RESET_ALL)

1.1 Init() 函数

init()接受一些 kwargs覆盖缺省行为:

https://www.cndba.cn/cndba/dave/article/3564

1)比如设置autoreset,其用来自动恢复到默认颜色。init(autoreset = False)。

2)比如wrap,在windows系统终端输出颜色要使用init(wrap=True)

https://www.cndba.cn/cndba/dave/article/3564

init(autoreset=True) # 初始化,并且设置颜色设置自动恢复

print(Fore.RED + 'some red text')

print(Back.GREEN + 'and with a green background')

print(Style.DIM + 'and in dim text')

#如果未设置autoreset=True,需要使用如下代码重置终端颜色为初始设置

#print(Fore.RESET + Back.RESET + Style.RESET_ALL)

print('back to normal now')

2 Colorama 使用示例

from colorama import init,Fore,Back,Style

init(autoreset=True)

class Colored(object):

# 前景色:红色 背景色:默认

def red(self, s):

return Fore.RED + s + Fore.RESET

# 前景色:绿色 背景色:默认

def green(self, s):

return Fore.GREEN + s + Fore.RESET

# 前景色:黄色 背景色:默认

def yellow(self, s):

return Fore.YELLOW + s + Fore.RESET

# 前景色:蓝色 背景色:默认

def blue(self, s):

return Fore.BLUE + s + Fore.RESET

# 前景色:洋红色 背景色:默认

def magenta(self, s):

return Fore.MAGENTA + s + Fore.RESET

# 前景色:青色 背景色:默认

def cyan(self, s):

return Fore.CYAN + s + Fore.RESET

# 前景色:白色 背景色:默认

def white(self, s):

return Fore.WHITE + s + Fore.RESET

# 前景色:黑色 背景色:默认

def black(self, s):

return Fore.BLACK

# 前景色:白色 背景色:绿色

def white_green(self, s):

return Fore.WHITE + Back.GREEN + s

def dave(self, s):

return Style.BRIGHT + Fore.GREEN + s

color = Colored()

print color.red('I am red!')

print color.green('I am gree!')

print color.yellow('I am yellow!')

print color.blue('I am blue!')

print color.magenta('I am magenta!')

print color.cyan('I am cyan!')

print color.white('I am white!')

print color.white_green('I am white green!')

print color.dave("www.cndba.cn")

运行效果图:

https://www.cndba.cn/cndba/dave/article/3564

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值