Python 结束无限循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18994912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ending an infinite while loop
提问by Blessoul
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 循环来从用户那里收集数据。根据文本文件的内容不断更新字典/列表。以供参考:
while (True):
IDs2=UpdatePoints(value,IDs2)
time.sleep(10)
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.
基本上,我的问题是我不知道我想要什么时候结束,但是在这个 while 循环运行之后我想使用收集的信息,而不是因为我的程序崩溃而丢失它。有没有一种简单、优雅的方法可以随时退出 while 循环?像按键盘上的某个键这样的东西会很棒。
采纳答案by Steve Howard
You can try wrapping that code in a try/except block, because keyboard interrupts are just exceptions:
您可以尝试将该代码包装在 try/except 块中,因为键盘中断只是例外:
try:
while True:
IDs2=UpdatePoints(value,IDs2)
time.sleep(10)
except KeyboardInterrupt:
print('interrupted!')
Then you can exit the loop with CTRL-C.
然后你可以用 CTRL-C 退出循环。
回答by eandersson
I think the easiest solution would be to catch the KeyboardInterruptwhen the interrupt key is pressed, and use that to determine when to stop the loop.
我认为最简单的解决方案是在按下中断键时捕获KeyboardInterrupt,并使用它来确定何时停止循环。
except KeyboardInterrupt:
break
The disadvantage of looking for this exception is that it may prevent the user from terminating the program while the loop is still running.
查找此异常的缺点是它可能会阻止用户在循环仍在运行时终止程序。
回答by Tristan
You could use exceptions. But you only should use exceptions for stuff that isn't supposed to happen. So not for this.
你可以使用异常。但是你应该只对不应该发生的事情使用异常。所以不是为了这个。
That is why I recommand signals:
这就是为什么我推荐信号:
import sys, signal
def signal_handler(signal, frame):
print("\nprogram exiting gracefully")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
you should put this on the beginning of your program and when you press ctrl+c wherever in your program it will shut down gracefully
你应该把它放在程序的开头,当你在程序的任何地方按下 ctrl+c 时,它会优雅地关闭
Code explanation:
代码说明:
You import sys
and signals
.
Then you make a function that executes on exit. sys.exit(0)
stops the programming with exit code 0 (the code that says, everything went good).
您导入sys
和signals
. 然后创建一个在退出时执行的函数。sys.exit(0)
使用退出代码 0 停止编程(该代码表示,一切顺利)。
When the program get the SIGINT either by ctrl-c or by a kill command in the terminal you program will shutdown gracefully.
当程序通过 ctrl-c 或终端中的 kill 命令获得 SIGINT 时,您的程序将正常关闭。
回答by Michael Green
I use python to track stock prices and submit automated buy/sell commands on my portfolio. Long story short, I wanted my tracking program to ping the data server for info, and place trades off of the information gathered, but I also wanted to save the stock data for future reference, on top of being able to start/stop the program whenever I wanted.
我使用 python 来跟踪股票价格并在我的投资组合中提交自动买入/卖出命令。长话短说,我希望我的跟踪程序能够 ping 数据服务器以获取信息,并对收集的信息进行权衡,但除了能够启动/停止程序之外,我还想保存股票数据以供将来参考每当我想要的时候。
What ended up working for me was the following:
最终为我工作的是以下内容:
trigger = True
while trigger == True:
try:
(tracking program and purchasing program conditions here)
except:
trigger = False
print('shutdown initialized')
df = pd.DataFrame...
save all the datas
print('shutdown complete')
etc.
等等。
From here, while the program is in the forever loop spamming away requests for data from my broker's API, using the CTRL-Ckeyboard interrupt function toggles the exception to the try loop, which nullifies the while loop, allowing the script to finalize the data saving protocol without bringing the entire script to an abrupt halt.
从这里开始,当程序处于永远循环从我的经纪人的 API 中发送垃圾数据请求时,使用CTRL-C键盘中断功能将异常切换到 try 循环,这使 while 循环无效,允许脚本完成数据保存协议不会让整个脚本突然停止。
Hope this helps!
希望这可以帮助!