本文使用的运行环境为 Python3
我们在用Python写命令行工具的时候,可以通过修改输出内容的颜色来让结构更清晰。
print("Error: this is an error.")
print("Warning: this is a warning.")
比如上面这段代码,默认输出Error和Warning颜色都是一样的。现在我们想让Error变成红色,Warning变成黄色,只要使用termcolor就可以很方便的做到。
from termcolor import *
print(colored("Error: this is an error.","red"))
print(colored("Warning: this is a warning.","yellow"))
使用termcolor的colored方法,就可以快捷的改变输出字符串的颜色了。在我的终端里效果如下。
![](https://img.haomeiwen.com/i2949750/f0c16a2b8e9f8c8d.png)
termcolor 可以通过pip直接安装。
pip install termcolor
termcolor除了可以设置字体颜色外,还可以设置高亮颜色,是否加粗,有下划线等。有兴趣的可以去https://pypi.python.org/pypi/termcolor了解一下。
网友评论