700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python无限循环怎么停止 如何在Python中安全地停止无限循环?

python无限循环怎么停止 如何在Python中安全地停止无限循环?

时间:2023-04-07 02:05:57

相关推荐

python无限循环怎么停止 如何在Python中安全地停止无限循环?

我有一个运行在无限循环上的脚本,它向数据库中添加了一些东西,并且做了一些我不能中途停止的事情,所以我不能只按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时,程序一直忽略我

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。