以下面的代码为例:
import signal
import time
def stop(signal, frame):
print("You pressed ctrl-c")
# stop counter()
def counter():
for i in range(20):
print(i+1)
time.sleep(0.2)
signal.signal(signal.SIGINT, stop)
while True:
if(input("Do you want to count? ")=="yes"):
counter()
我如何获得stop()
函数来杀死或破坏counter()
函数,以便它返回到提示符?
输出示例:
Do you want to count? no
Do you want to count? yes
1
2
3
4
5
6
7
You pressed ctrl-c
Do you want to count?
我正在使用Python 3.5.2。
答案 0 :(得分:1)
您可以在stop
中引发异常,该异常将暂停counter
的执行并搜索最近的异常处理程序(您在while True
循环中设置)。
即创建自定义异常:
class SigIntException(BaseException): pass
在stop
:
def stop(signal, frame):
print("You pressed ctrl-c")
raise SigIntException
并在while
循环中抓住它:
while True:
if(input("Do you want to count? ")=="yes"):
try:
counter()
except SigIntException:
pass
它的行为与你需要的方式相同。
答案 1 :(得分:1)
您可以使用KeyboardInterrupt
例外,而不是定义自己的SIGINT
处理程序:
while input("Do you want to count? ").strip().casefold() == "yes":
try:
counter()
except KeyboardInterrupt:
print("You pressed ctrl-c")