简体   繁体   English

从python命令在终端中打印彩色文本

[英]Printing colored text in terminal from python command

I have this python script in which I run in terminal. 我在终端中运行此python脚本。 Currently I am trying to incorporate colors, eg. 目前,我正在尝试合并颜色,例如。 if it is 'error', the text will be red, if it is 'working', the text will be green. 如果为“错误”,则文本将为红色;如果为“正常”,则文本将为绿色。

I have tried to refer to this post that I have found but when I tried to run it in my terminal using the following code: 我试图参考我发现的这篇文章 ,但是当我尝试使用以下代码在终端中运行它时:

print('\x1b[0;31;40m' + 'Error!' + '\x1b[0m')

I am getting red text with a greyish background instead of red text with black background. 我得到的是带有灰色背景的红色文本,而不是带有黑色背景的红色文本。 My terminal uses Python 2.6.2. 我的终端使用Python 2.6.2。

My question here is: 1. Is there any way to get rid of this 'greyish' background? 我的问题是:1.有什么办法摆脱这种“灰色”背景吗? 2. Instead of setting colors to the background, is there an 'invisible' option? 2.除了将颜色设置为背景之外,还有“不可见”选项吗? Eg. 例如。 if I run the command, the printed text background will conform to the terminal background? 如果我运行该命令,则打印的文本背景将与终端背景一致?

On a similar note, you can define colors and text decorators you want to use in a class and use them during printing instead of explicitly stating them in every print: 类似地,您可以定义要在类中使用的颜色和文本修饰符,并在打印期间使用它们,而不是在每次打印时都明确声明它们:

class Colors:
    Green, Red, White = '\033[92m', '\033[91m', '\033[0m'
    Bold, Italics = '\033[1m', '\x1B[3m'

print(Colors.Green + Colors.Bold + "I'm bold and green!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM