Print in terminal with colors?

2018-12-31 01:24发布

How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?

30条回答
妖精总统
2楼-- · 2018-12-31 01:57

For the characters

Your terminal most probably uses Unicode (typically UTF-8 encoded) characters, so it's only a matter of the appropriate font selection to see your favorite character. Unicode char U+2588, "Full block" is the one I would suggest you use.

Try the following:

import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
    char= unichr(index)
    try: its_name= unicodedata.name(char)
    except ValueError: its_name= "N/A"
    fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()

Examine the file later with your favourite viewer.

For the colors

curses is the module you want to use. Check this tutorial.

查看更多
查无此人
3楼-- · 2018-12-31 01:58

You want to learn about ANSI escape sequences. Here's a brief example:

CSI="\x1B["
print CSI+"31;40m" + "Colored Text" + CSI + "0m"

For more info see http://en.wikipedia.org/wiki/ANSI_escape_code

For a block character, try a unicode character like \u2588:

print u"\u2588"

Putting it all together:

print CSI+"31;40m" + u"\u2588" + CSI + "0m"
查看更多
不再属于我。
4楼-- · 2018-12-31 02:00

Building on @joeld answer, using https://pypi.python.org/pypi/lazyme pip install -U lazyme :

from lazyme.string import color_print
>>> color_print('abc')
abc
>>> color_print('abc', color='pink')
abc
>>> color_print('abc', color='red')
abc
>>> color_print('abc', color='yellow')
abc
>>> color_print('abc', color='green')
abc
>>> color_print('abc', color='blue', underline=True)
abc
>>> color_print('abc', color='blue', underline=True, bold=True)
abc
>>> color_print('abc', color='pink', underline=True, bold=True)
abc

Screenshot:

enter image description here


Some updates to the color_print with new formatters, e.g.:

>>> from lazyme.string import palette, highlighter, formatter
>>> from lazyme.string import color_print
>>> palette.keys() # Available colors.
['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
>>> highlighter.keys() # Available highlights.
['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
>>> formatter.keys() # Available formatter, 
['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']

Note: italic, fast blinking and strikethrough may not work on all terminals, doesn't work on Mac / Ubuntu.

E.g.

>>> color_print('foo bar', color='pink', highlight='white')
foo bar
>>> color_print('foo bar', color='pink', highlight='white', reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', bold=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
foo bar

Screenshot:

enter image description here

查看更多
牵手、夕阳
5楼-- · 2018-12-31 02:00

asciimatics provides a portable support for building text UI and animations:

#!/usr/bin/env python
from asciimatics.effects import RandomNoise  # $ pip install asciimatics
from asciimatics.renderers import SpeechBubble, Rainbow
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError


def demo(screen):
    render = Rainbow(screen, SpeechBubble('Rainbow'))
    effects = [RandomNoise(screen, signal=render)]
    screen.play([Scene(effects, -1)], stop_on_resize=True)

while True:
    try:
        Screen.wrapper(demo)
        break
    except ResizeScreenError:
        pass

Asciicast:

rainbow-colored text among ascii noise

查看更多
何处买醉
6楼-- · 2018-12-31 02:03

For Windows you cannot print to console with colors unless you're using the win32api.

For Linux it's as simple as using print, with the escape sequences outlined here:

Colors

For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:

#
查看更多
冷夜・残月
7楼-- · 2018-12-31 02:03

If you are using Django

>>> from django.utils.termcolors import colorize
>>> print colorize("Hello World!", fg="blue", bg='red',
...                 opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)

snapshot:

image

(I generally use colored output for debugging on runserver terminal so I added it.)

You can test if it is installed in your machine:
$ python -c "import django; print django.VERSION"
To install it check: How to install Django

Give it a Try!!

查看更多
登录 后发表回答