我正在使用 VSCode 进行 Python 编码。问题是 VSCode 以相同的格式和颜色打印任何输出(错误、警告和...)。
是否有任何扩展或工具来管理它?例如 PyCharm 打印红色错误、黄色警告等?
这不是 vscode 的问题,而是 bash/powershell/cmd 的一般问题(提醒一下,vscode 使用的控制台是由 powershell/bash 驱动的)。
我想我设法为您的问题找到了一个很好的解决方案/缓解措施。我发现这个答案给出了很好的结果。
说实话,我不喜欢这个 IPython 外观。从不做。经过一番研究,我想出了这个改进的代码
import sys
from IPython.core.ultratb import ColorTB
sys.excepthook = ColorTB()
Windows 上的颜色对我来说很合适: 但是每次添加这段代码都会......非常烦人。我们应该找到一种方法让它在 vscode 上的任何 .py 上运行。
我找到了一种方法来制作任何Python文件在运行任何脚本之前运行某行代码。 转到您的 python
PythonXY\Lib\site-packages
,其中 XY 是您的 python 版本。添加名为 exactly sitecustomize.py
的文件,并添加我们改进的脚本。
通过打印不存在的变量来测试它
print(a)
,你应该看到颜色:)
使用当前版本的 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")
查看这个图书馆。这将使您能够在终端中使用格式化输出。
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
。
print("\033[00m00: nothing\033[0m")
print("\033[01m01: bold?\033[0m")
print("\033[02m02: gray\033[0m")
print("\033[03m03: italic\033[0m")
print("\033[04m04: underline\033[0m")
print("\033[05m05-06: nothing\033[0m")
print("\033[07m07: inverted\033[0m")
print("\033[08m08: invisible?\033[0m")
print("\033[09m09: strike through\033[0m")
print("\033[10m10-20: nothing\033[0m")
print("\033[21m21: double underline\033[0m")
print("\033[22m22-29: nothing\033[0m")
print("\033[30m30: gray\033[0m")
print("\033[31m31: red\033[0m")
print("\033[32m32: green\033[0m")
print("\033[33m33: yellow\033[0m")
print("\033[34m34: blue\033[0m")
print("\033[35m35: magenta\033[0m")
print("\033[36m36: cyan\033[0m")
print("\033[37m37+: nothing\033[0m")