Python2.7 : How can I redirect texts with colors

标签 python python-2.7

我想在 Python 2.7 和 Linux 中为以下代码中的文本添加颜色。

import colorama
colorama.init( strip=False )

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

文本可以在终端中用颜色打印。但是,像“python script.py | cat”这样的管道后颜色会被删除。 我猜想 Python 根据输出 tty 删除颜色。如何实现像 grep --color=alwaysls --color=always 这样的行为。

最佳答案

这在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=Noneinit 。这就像传递--color=always一样而不是默认的 grepls .

<小时/>

当然你的代码没有调用 init首先。您应该是这样,但您却侥幸逃脱了,因为您可能不在 Windows 上:

Applications should initialise Colorama using:

from colorama import init init()

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.

关于Python2.7 : How can I redirect texts with colors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51229559/

相关文章:

python - Beautiful Soup - 下载 css 元素

json - Python 错误 : argument -c/--conf is required

python - 日期时间.strptime (‘2017-01-12T14:12:06.000-0500’ ,'%Y-%m-%dT%H:%M:%S.%f%Z' )

python - 从排序数组到排序多项式数组的算法

python - 在另一个模板中显示来自 Django View 的 HTML 表格

python - 如何让 Python 警告不良做法和可能的错误?

python - 当在 pyqt4 中按下修改键时,将所有键盘命令自动传输到嵌入式 mplayer 实例

python - 从 pexpect 中提取 stderr

python - 使用 python 合并两个电子表格 - 新工作表中的列源在源文件之间交替

python - 我正在使用 Python 中的基本脚本,但收到以下错误。这是什么意思?