【问题标题】:How to have colors in Terminal with Python in VSCode?如何在 VSCode 中使用 Python 在终端中显示颜色?
【发布时间】:2022-02-15 23:06:28
【问题描述】:

我正在使用 VSCode 来编写 Python 代码。问题是 VSCode 以相同的格式和颜色打印任何输出(错误、警告和...)。

是否有任何扩展或工具来管理它?例如像 PyCharm 打印错误用红色,警告用黄色等等?

【问题讨论】:

标签: python visual-studio-code terminal vscode-settings syntax-highlighting


【解决方案1】:

这不是 vscode 的问题,而是 bash/powershell/cmd 的一般问题(温馨提示,vscode 使用的控制台是由 powershell/bash 驱动的)。

我想我设法为您的问题找到了一个很好的解决方案/缓解措施。我发现了这个answer,结果很好。

TBH 我不喜欢这种 IPython 外观。从没干过。经过一番研究,我想出了这个改进的代码

import sys
from IPython.core.ultratb import ColorTB

sys.excepthook = ColorTB()

在 Windows 上哪个颜色对我来说很好: 但是每次添加这段代码会......非常烦人。我们应该找到一种方法让它在 vscode 上的任何 .py 上运行。

我找到了一种制作任何 Python 文件 run some line of code before running any script 的方法。 转到您的 python PythonXY\Lib\site-packages,其中 XY 是您的 python 版本。添加名为完全正确 sitecustomize.py 的文件,并添加我们改进的脚本。

通过打印不存在的变量print(a) 对其进行测试,您应该会看到颜色:)

【讨论】:

    【解决方案2】:

    看看这个library。这将使您能够在终端中使用格式化输出。

    【讨论】:

      【解决方案3】:

      VS Code 中没有这样的扩展。您必须使用 Python 库来执行此操作。要以不同颜色显示不同的日志,请使用pip install coloredlogs

      来自documenation的示例:

      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 用户并且如果上述方法不起作用,那么您必须使用 additional dependency pip install colorama

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-15
        • 2018-09-30
        • 2021-02-27
        • 1970-01-01
        • 2021-10-16
        • 2015-05-08
        • 2021-12-23
        • 1970-01-01
        相关资源
        最近更新 更多