首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Python中将彩色输出打印到终端?

如何在Python中将彩色输出打印到终端?
EN

Stack Overflow用户
提问于 2016-05-20 15:03:53
回答 6查看 227.5K关注 0票数 63

有没有类似于Perl的Python

代码语言:javascript
复制
print color 'red';
print <something>;
print color 'reset';

有空吗?

我正在使用这种方法:

代码语言:javascript
复制
"\x1b[1;%dm" % (<color code>) + "ERROR: log file does not exist" + "\x1b[0m"

我想要的是我应该能够设置所有打印消息的颜色,例如,

代码语言:javascript
复制
print color 'red'
function_print_something(<some message>)
print color 'reset'

这里的'function_print_something‘是我的python函数,它会在屏幕上打印一些格式化的日志消息。

EN

回答 6

Stack Overflow用户

发布于 2018-04-15 11:06:05

你可以在python 3中尝试一下:

代码语言:javascript
复制
from termcolor import colored
print(colored('Hello, World!', 'green', 'on_red'))

如果你使用的是windows操作系统,上面的代码可能不适用于你。然后你可以试试这段代码:

代码语言:javascript
复制
from colorama import init
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
init()

# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))

希望这能有所帮助。

票数 11
EN

Stack Overflow用户

发布于 2020-04-16 21:26:07

附注: Windows用户应该先运行os.system('color'),否则您将看到一些ANSI转义序列,而不是彩色输出。

票数 6
EN

Stack Overflow用户

发布于 2021-01-23 22:53:18

与这里列出的方法相比,我更喜欢系统附带的方法。在这里,我提供了一个没有第三方库的更好的方法。

代码语言:javascript
复制
class colors: # You may need to change color settings
    RED = '\033[31m'
    ENDC = '\033[m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'

print(colors.RED + "something you want to print in red color" + colors.ENDC)
print(colors.GREEN + "something you want to print in green color" + colors.ENDC)
print("something you want to print in system default color")

更多颜色代码,参考:Printing Colored Text in Python

祝你玩得开心!

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37340049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档