简体   繁体   English

给定#RRGGBB十六进制值的彩色Python输出

[英]Color Python output given #RRGGBB hex value

I've got a color from user in #RRGGBB hex format ( #D3D3D3 is light grey) and I'd like to color some output with it. 我从用户那里以#RRGGBB十六进制格式提供了一种颜色( #D3D3D3为浅灰色),我想用它为一些输出着色。 I imagine I write print("some text", color="#0000FF") and get blue colored output. 我想我写了print("some text", color="#0000FF")并得到蓝色输出。 Is it possible (ideally without 3rd party software)? 是否有可能(理想情况下,没有第三方软件)?

You can use the following escape sequences on a true-color aware terminal : 您可以在识别真彩色的终端上使用以下转义序列:

  • ESC[ … 38;2;<r>;<g>;<b> … m Select RGB foreground color ESC[ … 38;2;<r>;<g>;<b> … m选择RGB前景色
  • ESC[ … 48;2;<r>;<g>;<b> … m Select RGB background color ESC[ … 48;2;<r>;<g>;<b> … m选择RGB背景色

Thus you can write a function: 因此,您可以编写一个函数:

RESET = '\033[0m'
def get_color_escape(r, g, b, background=False):
    return '\033[{};2;{};{};{}m'.format(48 if background else 38, r, g, b)

and use this like: 并像这样使用:

print(get_color_escape(255, 128, 0) 
      + get_color_escape(80, 30, 60, True)
      + 'Fancy colors!' 
      + RESET)

You can get doubled horizontal or vertical resolution by using for example and both background and foreground colour. 通过使用以及背景和前景色,您可以获得水平或垂直分辨率的两倍。

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

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