如何在VSCode中使用Python在终端显示彩色?

19

我在使用VSCode编写Python代码,问题是无论是输出的错误信息、警告信息还是其他信息都以相同的格式和颜色显示。

是否有任何扩展或工具可以管理这个问题?例如像PyCharm那样,用红色打印错误、黄色打印警告等等?


1
https://marketplace.visualstudio.com/items?itemName=IBM.output-colorizer - Giorgos Myrianthous
谢谢,我测试了这个扩展!但是什么也没有改变!!! - Sina
为什么不使用Oh-my-zsh来优化你的终端呢? - pissall
@Sina,提供的任何解决方案有帮助到你吗? - barshopen
4个回答

8

这不是vscode的问题,而是bash/powershell/cmd的一般性问题(友情提醒:vscode使用的控制台由powershell/bash驱动)。

我认为我已经找到了一个很好的解决方案/缓解你的问题。我找到了这个答案,它给出了很好的结果。

enter image description here 说实话,我不喜欢这个IPython界面。从一些研究中,我想出了这段改进的代码。

import sys
from IPython.core.ultratb import ColorTB

sys.excepthook = ColorTB()

在 Windows 上,以下是我测试通过的代码高亮样式: enter image description here 但每次都添加这段代码会非常麻烦。我们需要找到一种方法,在 vscode 中运行任何 .py 文件时都可以使用。

我找到了一种方法,可以在运行任何脚本之前让任何 Python 文件运行某些代码行。前往你的 python 目录PythonXY\Lib\site-packages(其中 XY 是你的 python 版本),创建一个名为 exactly sitecustomize.py 的文件,并添加我们改进的脚本。

通过打印不存在的变量print(a)进行测试,你应该能够看到颜色 :)


(+1) 这对我很有效。关于 sitecustomize.py 文件,在 Windows 上,我将代码 import sys; from IPython.core.ultratb import ColorTB; sys.excepthook = ColorTB() 放在文件 C:\Users\<username here>\miniconda3\envs\<environment name here>\lib\site-packages\sitecustomize.py 中。有关 sitecustomize.py 文件的更多信息可以在此处找到。 - mhdadk

2

看看这个。使用它,你可以在终端中使用格式化输出。


2

使用当前版本的VS Code,可以选择打印彩色文本而无需安装额外模块。

print("\033[31mThis is red font.\033[0m")
print("\033[32mThis is green font.\033[0m")
print("\033[33mThis is yellow font.\033[0m")
print("\033[34mThis is blue font.\033[0m")
print("\033[37mThis is the default font. Anything above 37m is default. \033[0m")

0

在 VS Code 中没有这样的扩展。您必须使用 Python 库来实现。要显示不同颜色的不同日志,请使用 pip install coloredlogs

来自 文档 的示例:

import coloredlogs, logging
logger = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG')

logger.debug("this is a debugging message")
logger.info("this is an informational message")
logger.warning("this is a warning message")
logger.error("this is an error message")
logger.critical("this is a critical message")

如果你是Windows用户并且以上方法不起作用,那么你需要使用一个额外的依赖pip install colorama

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接