我注意到,在任何 python 3 程序上,无论它多么基本,如果你按下 CTRL c 它都会使程序崩溃,例如:
test=input("Say hello")
if test=="hello":
print("Hello!")
else:
print("I don't know what to reply I am a basic program without meaning :(")
如果您按 CTRL c 错误将是 KeyboardInterrupt 有没有办法阻止程序崩溃?
我想这样做的原因是因为我喜欢让我的程序防错,每当我想将某些内容粘贴到输入中时,我不小心按了 CTRL c 我必须再次检查我的程序......这很烦人。
最佳答案
Control-C
将引发 KeyboardInterrupt
不管你多么不想要它。但是,您可以非常轻松地处理错误,例如,如果您想要求用户在获取输入时按两次 control-c 以退出,您可以执行以下操作:
def user_input(prompt):
try:
return input(prompt)
except KeyboardInterrupt:
print("press control-c again to quit")
return input(prompt) #let it raise if it happens again
或者强制用户无论使用多少次都必须输入内容Control-C
你可以这样做:def user_input(prompt):
while True: # broken by return
try:
return input(prompt)
except KeyboardInterrupt:
print("you are not allowed to quit right now")
虽然我不会推荐第二个,因为使用快捷方式的人很快就会对你的程序感到恼火。
关于python-3.x - Python 3 键盘中断错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37887624/