Python如何自定义输出内容颜色

作者: handyTOOL | 来源:发表于2016-09-10 14:15 被阅读0次

本文使用的运行环境为 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方法,就可以快捷的改变输出字符串的颜色了。在我的终端里效果如下。


termcolor 可以通过pip直接安装。

pip install termcolor

termcolor除了可以设置字体颜色外,还可以设置高亮颜色,是否加粗,有下划线等。有兴趣的可以去https://pypi.python.org/pypi/termcolor了解一下。

相关文章

网友评论

    本文标题:Python如何自定义输出内容颜色

    本文链接:https://www.haomeiwen.com/subject/dzmyettx.html