我注意到,在任何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键,我不得不浏览我的程序,again..Which是非常烦人的。
发布于 2016-06-18 04:14:50
无论您多么不希望KeyboardInterrupt,Control-C都会抛出它。但是,您可以很容易地处理该错误,例如,如果您想要求用户按两次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")虽然我不推荐第二个,因为使用快捷键的人很快就会对你的程序感到恼火。
发布于 2021-08-27 12:12:20
此外,在你的程序中,如果有人输入" hello ",它不会回复hello,因为第一个字母是大写的,所以你可以使用:
if test.isupper == True:
print("Hello!")https://stackoverflow.com/questions/37887624
复制相似问题