gpt4 book ai didi

python - 全局关闭 Colorama 颜色代码

转载 作者:行者123 更新时间:2023-12-04 09:21:19 24 4
gpt4 key购买 nike

Python 的 colorama非常适合装扮终端输出: enter image description here

如您所见,这将添加 ANSI 代码并显示颜色,即使将日志记录模块用于标准输出也是如此。我用这样的语句来这样做:

logging.info(f"{Fore.CYAN}Query received from {current_user.username}{Style.RESET_ALL}")

但是,如果我要将日志记录模块指向一个文件,那么我到处都会得到一大堆我显然不想要的 ANSI 代码。

如果日志记录到文件被打开(或编写一个日志记录函数做同样的事情),如果没有到处写if语句来抑制colorama,有没有办法在顶部全局关闭colorama脚本?

最佳答案

您可以暂时将 ForeBackStyle 命名空间替换为包含常量空字符串的命名空间。

class DummyFore:
BLACK=RED=GREEN=YELLOW=BLUE=MAGENTA=CYAN=WHITE=RESET=''

saved_Fore, Fore = Fore, DummyFore

logging.info(f"{Fore.CYAN}Query received from {current_user.username}{Style.RESET_ALL}") # should insert empty strings for the colour codes
Fore = saved_Fore
del saved_Fore # just to be thorough

它还应该可以将保存-恢复逻辑包装在上下文管理器中:

@contextlib.contextmanager
def without_colorama():
global Fore
saved_Fore, Fore = Fore, DummyFore
yield
Fore = saved_Fore
# since saved_Fore is now a local, no need to `del`

with without_colorama():
logging.info(f"{Fore.CYAN}Query received from {current_user.username}{Style.RESET_ALL}")

在所有示例代码中,我只处理了 Fore 命名空间;其他留作练习。

关于python - 全局关闭 Colorama 颜色代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63100603/

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