我最近(2020 年 5 月 2 日)使用 Anaconda2-Spyder(Python2.7)在 Windows-10 中遇到了同样的问题。我是使用 Spyder 的新手。通过尝试 stackoverflow 中列出的几个建议,我尝试了多种方法来让 [break] 或 [ctrl-c] 按预期工作。似乎没有任何效果。但是,我最终注意到的是程序在“KeyboardInterrupt”捕获后找到的行上停止。
【解决方案】:在调试器工具(菜单项或图标功能)中选择【运行当前行】或【继续执行】,程序的其余部分执行,程序正常退出。我构建了以下内容来试验键盘输入。
def Test(a=0,b=0):
#Simple program to test Try/Catch or in Python try/except.
#[break] using [Ctrl-C] seemed to hang the machine.
#Yes, upon [Ctrl-C] the program stopped accepting User #
Inputs but execution was still "hung".
def Add(x,y):
result = x+y
return result
def getValue(x,label="first"):
while not x:
try:
x=input("Enter {} value:".format(label))
x = float(x)
continue
except KeyboardInterrupt:
print("\n\nUser initiated [Break] detected." +
"Stopping Program now....")
#use the following without <import sys>
raise SystemExit
#otherwise, the following requires <import sys>
#sys.exit("User Initiated [Break]!")
except Exception:
x=""
print("Invalid entry, please retry using a " +
"numeric entry value (real or integer #)")
continue
return x
print ("I am an adding machine program.\n" +
"Just feed me two numbers using "Test(x,y) format\n" +
"to add x and y. Invalid entries will cause a \n" +
"prompt for User entries from the keyboard.")
if not a:
a = getValue(a,"first")
if not b:
b = getValue(b,"second")
return Add(a,b)