E_J*_*E_J 2 ctrl keyboardinterrupt python-3.x
我注意到在任何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 :(")
Run Code Online (Sandbox Code Playgroud)
如果按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
Run Code Online (Sandbox Code Playgroud)
或强迫用户输入内容,无论他们使用多少次,control-c您都可以执行以下操作:
def input_noQuit(prompt):
while True: #broken by return
try:
return input(prompt)
except KeyboardInterrupt:
print("you are not allowed to quit right now")
Run Code Online (Sandbox Code Playgroud)
虽然我不推荐第二个,因为使用快捷方式的人会很快对你的程序感到恼火.