gpt4 book ai didi

Python2.7 : How can I redirect texts with colors

转载 作者:行者123 更新时间:2023-12-01 09:16:18 25 4
gpt4 key购买 nike

我想在 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 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.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com