Python2.7:如何用颜色重定向文本

2024-06-26 00:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python2.7和Linux中为以下代码中的文本添加颜色。你知道吗

import colorama
colorama.init( strip=False )

print( colorama.Fore.RED + "Hello World!" + colorama.Fore.RESET )

文本可以用不同颜色在终端上打印。但是,在管道之后颜色会被移除,比如“python”脚本.py|“猫”。 我猜Python会根据输出tty移除颜色。如何实现像grep --color=alwaysls --color=always这样的行为。你知道吗


Tags: 代码文本importfalsehelloinit颜色linux
1条回答
网友
1楼 · 发布于 2024-06-26 00:19:00

这在库的readme中有清楚的解释。你知道吗

init() accepts some **kwargs to override default behaviour.

init(strip=None):

Pass True or False to override whether ansi codes should be stripped from the output. The default behaviour is to strip if on Windows or if output is redirected (not a tty).

init(convert=None)

Pass True or False to override whether to convert ANSI codes in the output into win32 calls. The default behaviour is to convert if on Windows and output is to a tty (terminal).

假设您不在Windows上,那么答案是将strip=False而不是默认的strip=None传递给init。这就像传递 color=always而不是默认值给grepls。你知道吗


当然,您的代码一开始并没有调用init。你应该这样做,但你却逍遥法外,因为你可能不在Windows上:

Applications should initialise Colorama using:

from colorama import initinit()

On Windows, calling init() will filter ANSI escape sequences out of any text sent to stdout or stderr, and replace them with equivalent Win32 calls.

On other platforms, calling init() has no effect (unless you request other optional functionality; see “Init Keyword Args”, below). By design, this permits applications to call init() unconditionally on all platforms, after which ANSI output should just work.

相关问题 更多 >