如何在VS Code终端中为Python更改错误文本颜色

huangapple go评论77阅读模式
英文:

How to change error text color in vs code terminal for python

问题

I would like to change the color of text in error to red and/or multiple color for different parts of showing error.

My Vs Code Terminal currently look this this,
如何在VS Code终端中为Python更改错误文本颜色

I would like something like this made using the rich module, 如何在VS Code终端中为Python更改错误文本颜色 Something like this of pycharm.
如何在VS Code终端中为Python更改错误文本颜色, or, preferably, like Spyder's look 如何在VS Code终端中为Python更改错误文本颜色

Adding this "terminal.ansiRed":"#d84240" is not working.

英文:

I would like to change the color of text in error to red and/or multiple color for different parts of showing error.

My Vs Code Terminal currently look this this,
如何在VS Code终端中为Python更改错误文本颜色

I would like something like this made using rich module, 如何在VS Code终端中为Python更改错误文本颜色 Something like this of pycharm.
如何在VS Code终端中为Python更改错误文本颜色, or, preferably, like Spyder's looj 如何在VS Code终端中为Python更改错误文本颜色

Adding this "terminal.ansiRed":"#d84240" is not working

答案1

得分: 3

Both PyCharm 和 Spyder 在可能的情况下都使用 ipython 解释器(如果安装了 ipython 模块)。所以,交互式 shell 的最简单解决方案是确保它已安装在您的 venv 中,然后调用 ipython 而不是常规的 python 解释器。

正如您在我的截图中所见,VsCode 正在运行一个普通的 shell。Python 解释器不会创建任何颜色,但IPython 会自行处理颜色。
如何在VS Code终端中为Python更改错误文本颜色

至于在脚本内部着色错误/异常,您需要以程序方式处理它。最简单的方法是安装 pretty_errors 模块,然后您将希望代码中有错误,因为它们会变得如此美丽 ;):
如何在VS Code终端中为Python更改错误文本颜色

英文:

Both PyCharm and Spyder are using ipython interpreter when possible (the ipython module is installed).
So the most simple solution for interactive shell is to make sure it is installed in your venv and invoke ipython instead of regular python interpreter.

As you can see in my screenshot VsCode is running a regular shell. Python interpreter does not create any colors, but IPython handles colors by itself.
如何在VS Code终端中为Python更改错误文本颜色

As for coloring errors/exceptions from within your scripts, you need to handle it programmatically. The easiest way is to install the pretty_errors module, and then you will want to have errors in your code just because they will be so beautiful 如何在VS Code终端中为Python更改错误文本颜色 :
如何在VS Code终端中为Python更改错误文本颜色

答案2

得分: 1

You can set any colour as you wish in the python code (ANSI escape sequences).

def print_error(message):
    print("3[33m{}3[0m".format(message)) # 3[33m sets the color to yellow

try:
    result = 10 / 0
except Exception as e:
    print_error("An error occurred: {}".format(e))
refer the table for colour code:
Text Color    Foreground Code
Black         3[30m
Red           3[31m
Green         3[32m
Yellow        3[33m
Blue          3[34m
Magenta       3[35m
Cyan          3[36m
White         3[37m
Bright Black  3[90m
Bright Red    3[91m
Bright Green  3[92m
Bright Yellow 3[93m
Bright Blue   3[94m
Bright Magenta3[95m
Bright Cyan   3[96m
Bright White  3[97m
英文:

You can set any colour as you wish in the python code (ANSI escape sequences).

def print_error(message):
    print("\033[33m{}\033[0m".format(message)) # 3[33m sets the color to yellow

try:
    result = 10 / 0
except Exception as e:
    print_error("An error occurred: {}".format(e))
refer the table for colour code:
Text Color	Foreground Code
Black	       3[30m
Red	           3[31m
Green	       3[32m
Yellow	       3[33m
Blue	       3[34m
Magenta	       3[35m
Cyan	       3[36m
White	       3[37m
Bright Black   3[90m
Bright Red	   3[91m
Bright Green   3[92m
Bright Yellow  3[93m
Bright Blue    3[94m
Bright Magenta 3[95m
Bright Cyan	   3[96m
Bright White   3[97m

答案3

得分: 1

这部分内容不需要翻译。

英文:

So, coloring things in the terminal from Python has been answered a lot of times so I assume you want to make VSCode use colors for Python exceptions without adding more packages and with minimal changes to your code. (For completeness I have added an excellent method to color the traceback like your Spyder example if you are allowed to add the Pygments package below.)

Colored Python Exceptions in VSCode Windows Terminal using ANSI codes

The VSCode Windows Terminal supports the ANSI control codes quite well, so adding one before and after the printing of the Python traceback in Python's exit handler will color (and possibly format) the output.

Colors tested with foo.py:

print('3[31mTest3[0m')

You can then create a custom exit handler (see sys.excepthook) to add the colors and reset them afterwards at the beginning of your Python program:

def set_highlighted_excepthook():
    import sys, traceback

    def myexcepthook(type, value, tb):
        tbtext = ''.join(traceback.format_exception(type, value, tb))
        sys.stderr.write('3[31m' + tbtext + '3[0m')

    sys.excepthook = myexcepthook

set_highlighted_excepthook()

For more codes to set colors and italics etc. refer to the ANSI codes: SGR (Select Graphic Rendition) parameters. E.g. to set bold/bright red use code 1 followed by 31: \033[1;31m. You can have as many codes as you like as long as you start with \033[, separate each code with ; and end with m. Always remember to print \033[0m to reset everything back to normal at the end!

Better Colored Python Exceptions in VSCode Windows Terminal using Pygments:

Install the amazing Pygments package which has a language lexer for Python Tracebacks:

pip.exe install pygments

Then set a new excepthook to print through Pygments Python Traceback Lexer and apply your chosen style:

def set_highlighted_excepthook():
    import sys, traceback
    from pygments import highlight
    from pygments.lexers import PythonTracebackLexer
    from pygments.formatters import Terminal256Formatter

    formatter = Terminal256Formatter(style='xcode')

    def myexcepthook(type, value, tb):
        tbtext = ''.join(traceback.format_exception(type, value, tb))
        sys.stderr.write(highlight(tbtext, PythonTracebackLexer(), formatter))

    sys.excepthook = myexcepthook


set_highlighted_excepthook()

Credit: Martijn Pieters https://stackoverflow.com/a/14776693/13269963 updated for 256 Color support.

To change the style change the string style='xcode' to one of Pygments' styles or create your own!

答案4

得分: 1

可以做到正如原帖的截图所示的功能,即为整个虚拟环境安装 rich 的 traceback 处理程序。

  1. 执行 python -c 'import site; print(site.getsitepackages()[0])' (来源)
  2. 在步骤 1 中获取的目录内创建 sitecustomize 目录。
  3. 在该目录内创建名为 __init__.py 的文件,内容如下:
from rich.traceback import install
install()

然后在 VS Code 中执行命令 "Python: Select Interpreter",选择来自 venv 的 Python 解释器。

从现在开始,在嵌入式终端中执行文件或在 Python 解释器中执行区域时,tracebacks 将会是彩色的。

英文:

It is possible to do exactly what the screenshot of the OP shows, namely install rich's traceback handler, for the whole virtual environment.

  1. Execute python -c 'import site; print(site.getsitepackages()[0])' (source)
  2. Create the directory sitecustomize within the directory obtained in 1.
  3. Within this directory create the file __init__.py with the contents
from rich.traceback import install
install()

Then in VS Code execute the command "Python: Select Interpreter" and select the Python interpreter from the venv.

From now on when executing a file in the embedded terminal or a region in the Python interpreter tracebacks will be colorful.

答案5

得分: 0

首先查看不同的选项:颜色选项

在 vs-code 中,您可以通过访问 settings.json 文件来编辑它们。 (在 Windows/Linux 上 - 文件 > 首选项 > 设置或快捷键(ctrl,))。

在那里,您有更改颜色的能力。

希望这有所帮助!

英文:

First have a look at the diff. options: color options.

In vs-code you can edit them by accessing the settings.json file. (On Windows/Linux - File > Preferences > Settings or Shortcut(ctrl,)).

There you have the ability to change your colorization.

Hope this helps!

huangapple
  • 本文由 发表于 2023年5月10日 22:23:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定