如何将彩色文本打印到终端? [英] How to print colored text to the terminal?

查看:111
本文介绍了如何将彩色文本打印到终端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 中将彩色文本输出到终端?

How can I output colored text to the terminal in Python?

推荐答案

这在某种程度上取决于您使用的平台.最常见的方法是打印 ANSI 转义序列.举个简单的例子,这里有一些 Python 代码来自 Blender 构建脚本:

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

要使用这样的代码,您可以执行以下操作:

To use code like this, you can do something like:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

或者,使用 Python 3.6+:

Or, with Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

这将适用于包括 OS X、Linux 和 Windows 在内的 Unix(前提是您使用 ANSICON,或在Windows 10 如果您启用 VT100 仿真).有用于设置颜色、移动光标等的 ANSI 代码.

This will work on unixes including OS X, Linux and Windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.

如果您对此感到复杂(听起来就像您正在编写游戏一样),您应该查看诅咒";模块,它为您处理了很多复杂的部分.Python Curses HowTO 是一个很好的介绍.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

如果您不使用扩展 ASCII(即不在 PC 上),您会被 ASCII 字符困在 127 以下,而#"或@"可能是块的最佳选择.如果您可以确保您的终端使用 IBM 扩展 ASCII 字符集,那么您还有更多选项.字符 176、177、178 和 219 是块字符".

If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".

一些现代基于文本的程序,例如Dwarf Fortress",以图形模式模拟文本模式,并使用经典 PC 字体的图像.您可以在 Dwarf Fortress Wiki 上找到其中一些可以使用的位图,请参阅(用户制作的tilesets).

Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

文本模式演示竞赛有更多资源可以做文本模式下的图形.

The Text Mode Demo Contest has more resources for doing graphics in text mode.

这篇关于如何将彩色文本打印到终端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆