如何在Python中打印彩色文本? [英] How to print colored text in Python?

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

问题描述

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

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

推荐答案

这在某种程度上取决于您所使用的平台.最常见的方法是打印ANSI转义序列.举一个简单的例子,这是

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'
    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)

或者,对于Python3.6 +:

or, with Python3.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.

如果您对此感到复杂(听起来就像在编写游戏一样),则应该查看"curses"模块,该模块为您处理了许多复杂的部分. 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上),则您将被困在127以下的ASCII字符中,并且'#'或'@'可能是您最好的选择.如果您可以确保终端使用的是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".

一些现代的基于文本的程序,例如矮人要塞",以图形模式模拟文本模式,并使用经典PC字体的图像.您可以在矮人要塞Wiki 中找到一些可以使用的位图,请参见(

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.

嗯..我认为这个答案有些不为所动.不过,我正在计划一个史诗般的基于文本的冒险游戏.祝您彩色文字好运!

Hmm.. I think got a little carried away on this answer. I am in the midst of planning an epic text-based adventure game, though. Good luck with your colored text!

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

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