我有一个运行在无限循环上的脚本,它向数据库中添加了一些东西,并且做了一些我不能中途停止的事情,所以我不能只按ctrl+C就停止它。
我希望能够以某种方式停止while循环,但让它在停止之前完成最后一次迭代。
让我澄清一下:
我的代码如下:while True:
does something
does more things
does more things
我希望能够在结束或开始时中断while循环,但不能在两次操作之间中断,因为那样做会很糟糕。
我不希望它在每次迭代后都问我是否想继续。
感谢您的回答,我非常感谢,但我的实现似乎并不奏效:def signal_handler(signal, frame):
global interrupted
interrupted = True
class Crawler():
def __init__(self):
# not relevent
def crawl(self):
interrupted = False
signal.signal(signal.SIGINT, signal_handler)
while True:
doing things
more things
if interrupted:
print("Exiting..")
break
当我按ctr+c时,程序一直忽略我