【问题标题】:Raise exception without quitting the program在不退出程序的情况下引发异常
【发布时间】:2020-10-28 02:35:31
【问题描述】:

我在 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

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

【问题讨论】:

  • 而程序在打印错误后应该怎么做?
  • 如果你只关心颜色,那么你可以使用像colorize这样的包
  • 您好,您是否考虑过使用 try ... catch 语句。如果你提供一个你想要做什么的例子,那么很容易说明 try catch 语句是如何适应它的。最好的问候
  • @wovano 应该会继续正常
  • @MZ 我尝试了所有的着色包,但打印的内容类似于hello[1]re[[3]

标签: python python-3.x python-3.7 nameerror raiseerror


【解决方案1】:

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

from termcolor import colored

Python 2:

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

或者在 Python 3 中:

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

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

【讨论】:

  • 虽然这可能会打印出漂亮的错误消息,但它并不能真正回答“引发异常而不退出”的问题。它只是打印一条(错误)消息。如果这是想要的功能,它可能是 OP 的一个很好的解决方案,但是这个问题有点误导恕我直言。
  • NB:Python 2 代码真的还需要吗? Python 2 已经过了它的生命周期,问题被标记为 python-3.x。
  • 感谢您的想法,但这会打印给我:[31mhello[0m [32mworld[0m
【解决方案2】:

在没有更多细节的情况下,你可以尝试这样的事情:

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

但是,这并不是应该使用异常的确切方式。

【讨论】:

    【解决方案3】:

    经过长时间的研究,我找到了答案: 这不会引发错误,但会在终端和 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"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2011-03-19
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多