结束无限的while循环 [英] Ending an infinite while loop
问题描述
我目前拥有基本运行无限while循环以从用户收集数据的代码.根据文本文件的内容不断更新字典/列表.供参考:
I currently have code that basically runs an infinite while loop to collect data from users. Constantly updating dictionaries/lists based on the contents of a text file. For reference:
while (True):
IDs2=UpdatePoints(value,IDs2)
time.sleep(10)
基本上,我的问题是我不知道何时结束,但是在运行while循环之后,我想使用收集的信息,而不会因为程序崩溃而丢失信息.是否有一种简单,优雅的方法可以在我需要的时候简单地退出while循环?像按键盘上的某个键一样棒.
Basically, my problem is that I do not know when I want this to end, but after this while loop runs I want to use the information collected, not lose it by crashing my program. Is there a simple, elegant way to simply exit out of the while loop whenever I want? Something like pressing a certain key on my keyboard would be awesome.
推荐答案
您可以尝试将代码包装在try/except块中,因为键盘中断只是个例外:
You can try wrapping that code in a try/except block, because keyboard interrupts are just exceptions:
try:
while True:
IDs2=UpdatePoints(value,IDs2)
time.sleep(10)
except KeyboardInterrupt:
print('interrupted!')
然后您可以使用CTRL-C退出循环.
Then you can exit the loop with CTRL-C.
这篇关于结束无限的while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!