使用 SIGINT 终止 Python 中的函数 3
Using SIGINT to kill a function in Python 3
以下面的代码为例:
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()
函数,使其 returns 出现提示?
输出示例:
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.
您可以在 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
它的行为符合您的需要。
您可以使用 KeyboardInterrupt
异常而不是定义您自己的 SIGINT
处理程序:
while input("Do you want to count? ").strip().casefold() == "yes":
try:
counter()
except KeyboardInterrupt:
print("You pressed ctrl-c")
以下面的代码为例:
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()
函数,使其 returns 出现提示?
输出示例:
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.
您可以在 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
它的行为符合您的需要。
您可以使用 KeyboardInterrupt
异常而不是定义您自己的 SIGINT
处理程序:
while input("Do you want to count? ").strip().casefold() == "yes":
try:
counter()
except KeyboardInterrupt:
print("You pressed ctrl-c")