gpt4 book ai didi

python - 无法在 Python 中中止 (ctrl+c)

转载 作者:行者123 更新时间:2023-11-30 22:04:20 25 4
gpt4 key购买 nike

如果输入不是整数,我编写此代码是为了不断请求更多输入。但是,当我尝试在 python 交互式 session 中中止它时,它不断要求输入。

为什么它会这样做,即使我按了 Ctrl+C,这意味着中止。

def get_size(text):
while True:
try:
i = int(input(text))
if i >= 0 and i<24:
break
except:
pass
return i

a = get_size("Input: ")

最佳答案

当您按 Ctrl + C 时,Python 解释器会捕获中断并引发 KeyboardInterrupt 异常。因为你的 except 相当于 except BaseException 并且 KeyboardInterrupt BaseException 的子类,所以你的 except 将捕获KeyboardInterruptexcept block 中没有异常处理(例如重新引发),因此程序将继续。

至少将 except 更改为 except Exception,因为异常是 BaseException 的子类,但不是 的子类>Exception(KeyboardInterruptSystemExitGeneratorExit)并不是真正要被吞掉的。在某些罕见的情况下,在重新饲养它们之前捕获它们并进行一些清理是有意义的。但几乎没有一个用例可以捕获它们并且不再将它们提升。

Python documentation actually contains a hierarchy visualization of built-in exceptions这可能会很方便:

BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
...

您可能会注意到 except Exception 还可以捕获一些您可能无法恢复的异常。例如,MemoryErrorSyntaxErrorSystemError 通常表示出现了(确实)错误,并且这些错误不应该被吞掉,因为这些可能无法“恢复”(至少在大多数情况下)。

这意味着您应该观察代码可能抛出哪些异常以及在什么情况下抛出异常,然后决定可以从中恢复哪些异常。

就您而言:

  • input() 不会失败,因此您不妨将其放在 try 之外。
  • 同样,您也不会期望比较会失败,因此这些也可以放在 try block 之外。因为您只想在 try 成功时运行该代码,所以您需要保护它,例如在 tryelse block 中。
  • 如果类型不受支持,int() 可能会因 TypeError 而失败,但 input 始终返回字符串。 String 是 int() 可接受的类型,因此人们不会期望这种情况发生。
  • 因此,您可能在这里遇到的唯一“预期”异常是 ValueError。如果字符串无法被解释为整数,则会抛出该错误。

所以我会使用:

def get_size(text):
while True:
input_text = input(text)
try:
i = int(input_text)
except ValueError:
pass
else:
if 0 <= i < 24:
return i

或者,如果您不需要 else block ,您也可以在 except block 中继续:

def get_size(text):
while True:
input_text = input(text)
try:
i = int(input_text)
except ValueError:
continue
if 0 <= i < 24:
return i

您使用哪一个主要取决于您的偏好。两者的工作原理应该相同。

总结一下:

  • 确定(从您的角度来看)允许失败的最少量代码,不要在 try block 内放置任何其他内容。
  • 确保仅捕获“可恢复”异常。在大多数情况下,异常类型就足够了。但有时检查异常消息以确保它确实是您想要捕获的异常可能是有意义的。
  • 切勿使用 except: except BaseException:。唯一的异常(exception)是,如果您确实想捕获 SystemExit、KeyboardInterrupt 或 GeneratorExit 并知道如何正确处理它们。您可能会逃脱 except Exception 的惩罚,但对于您想要定期使用(或在生产代码中)的任何代码,您应该投入时间来查找更合适的异常。

关于python - 无法在 Python 中中止 (ctrl+c),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53325987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com