在 Spyder 中正确终止脚本而不显示错误消息

Properly terminate script without error message in Spyder

所以对于我在 python 中的项目,我将两个输入作为整数值,比如 a 和 b。现在代码如下:

import sys
a = input("enter a")
b = input("enter b")
if a < b:
    print(" enter a greater than b and try again")
    sys.exit()

# Rest of the code is here

现在可以正常工作了。但是会创建一个额外的语句

An exception has occurred, use %tb to see the full traceback.

SystemExit

而且我不希望这样,因为用户可能认为代码的功能不正常。那么有没有什么方法可以不显示此语句或任何其他函数可以退出代码而不打印除了我写的行之外的任何内容?

注意 我试过 exit() 但它继续执行它下面的代码。另外,我注意到 this related question 但此处列出的方法在这种情况下不起作用。

编辑:我正在添加更多信息。我需要把这个退出函数放到一个用户定义的函数中,这样每次用户输入一些错误的数据时,代码就会调用这个用户定义的函数并退出代码。 如果我尝试将我的代码放在 if else 语句中,例如

def end():
    print("incorrect input try again")
    os.exit()

a = input("enter data")
if a < 10:
    end()
b = input ("enter data")
if b < 20:
   end()
# more code here

我不知道为什么,但我什至无法在最后定义这个用户定义的函数,因为它引发了未定义函数 end() 的错误。我在 Windows.

上使用 Python 和 Spyder

您可以使用os._exit()

a = int(input("enter a"))
b = int(input("enter b"))
if a < b:
    print(" enter a greater than b and try again")
    os._exit(0)

这似乎工作得很好:

import sys

def end():
    print("incorrect input try again")
    sys.exit(1)

a = input("enter data")
if int(a) < 10:
    end()
b = input ("enter data")
if int(b) < 20:
    end()

我使用了 sys.exit 并修复了您的条件以避免将字符串与整数进行比较。我在输出中看不到任何其他消息。只有这个:

>py -3 test2.py
enter data1
incorrect input try again
>

另请注意 python 文档中的这条引述:

The standard way to exit is sys.exit(n). [os]_exit() should normally only be used in the child process after a fork().

它也适用于 repl