0

我在 Windows 上并使用 python 3.7.7。我正在尝试制作一种高尔夫语言。在那个 e。如果您提出这样的异常(要清楚NameError):

raise NameError("Your input was not recognized as a function, variable or  datatype")

然后程序自动退出。当我尝试这个时:

 print(NameError("Your input was not recognized as a function, variable or  datatype"))

然后它会打印错误但不完全并且不是这样的红色: Your input was not recognized as a function, variable or datatype

有没有办法让程序不退出并打印真正的错误?

4

3 回答 3

1

In the absence of more details, you can try something like this:

try:
    raise(NameError("Your input was not recognized as a function, variable or  datatype"))
except Exception as e:
    print(repr(e))

However, this is not exactly how exceptions should be used.

于 2020-07-07T19:04:33.987 回答
0

经过长时间的研究,我找到了答案:这不会引发错误,但会在终端和 shell 中打印彩色错误

  1. 使用 pip安装CLINT
pip install clint
  1. 在 Python 中
import sys
try:
    sys.stdout.shell.write("Your input was not recognized as a variable, function or datatype\n", "COMMENT")
except AttributeError:
    puts(colored.red("Your input was not recognized as a variable, function or datatype"))
于 2020-07-08T13:35:24.010 回答
0

我很惊讶没有人提到 Python termcolor 模块。用法很简单:

from termcolor import colored

蟒蛇2:

print colored('hello', 'red'), colored('world', 'green')

或者在 Python 3 中:

print(colored('hello', 'red'), colored('world', 'green'))

除了使用“try-except”语句之外,毕竟你可以在不退出程序的情况下引发异常,只需在 except 子句中添加一些东西。

于 2020-07-07T19:02:06.927 回答