How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
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:
To use code like this, you can do something like
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.
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.
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".
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!
I'm surprised no one has mentioned the Python termcolor module. Usage is pretty simple:
Or in Python 3:
It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...
Print a string that starts a color/style, then the string, then end the color/style change with
'\x1b[0m'
:Get a table of format options for shell text with following code:
Light-on-dark example (complete)
Dark-on-light example (partial)
I ended up doing this, I felt it was cleanest:
https://raw.github.com/fabric/fabric/master/fabric/colors.py
Define a string that starts a color and a string that ends the color, then print your text with the start string at the front and the end string at the end.
This produces the following in
bash
, inurxvt
with a Zenburn-style color scheme:Through experemintation, we can get more colors:
Note:
\33[5m
and\33[6m
are blinking.This way we can create a full color collection:
Here is the code to generate the test: