Loops 在x分钟内中断While True循环

Loops 在x分钟内中断While True循环,loops,dataframe,Loops,Dataframe,我试图找到一种方法在x分钟后打破while-true循环,下面是我的代码。并通过i函数将新数据追加到数据帧中 import time import bs4 import requests from bs4 import BeautifulSoup import pandas as pd price=[] pricetime=[] r=requests.get('https://finance.yahoo.com/quote/SPY?p=SPY&.tsrc=fin-srch') so

我试图找到一种方法在x分钟后打破while-true循环,下面是我的代码。并通过i函数将新数据追加到数据帧中

import time
import bs4
import requests
from bs4 import BeautifulSoup
import pandas as pd

price=[]
pricetime=[]


r=requests.get('https://finance.yahoo.com/quote/SPY?p=SPY&.tsrc=fin-srch')
soup = bs4.BeautifulSoup(r.text,'lxml')
current_price = soup.find_all('div',{'class':"My(6px) Pos(r) smartphone_Mt(6px)"})[0].find('span').text

def i():
    while True:
        print(current_price + str(time.ctime()))
        price.append(current_price)
        pricetime.append(time.ctime())
        time.sleep(10)


您可以在超时[1]的情况下使用线程模块:

初始化一个事件对象stop_Event,并在每个循环中检查是否设置了此stop_Event。 初始化线程对象Thread_i,并将自己的函数作为目标传递。 启动线程并等待10分钟。 设置stop_事件以使功能停止。 最终代码如下所示:

from threading import Thread, Event
import time

# Event object used to send signals from one thread to another
stop_event = Event()

def i():
    """
    Function that should timeout after 10 mins.
    """
    while True:
        # move your code here

        # Here we make the check if the other thread sent a signal to stop execution.
        if stop_event.is_set():
            break

if __name__ == '__main__':
    # We create another Thread, set the target to be your function.
    i_thread = Thread(target=i)

    # Here we start the thread and we wait 10 mins before the code continues to execute.
    i_thread.start()
    i_thread.join(timeout=10*60)

    # We send a signal that the other thread should stop.
    stop_event.set()

[1]

我觉得Python标签应该是合适的,你不觉得吗?很有魅力,谢谢。所以基本上,我们运行两个线程,一个用于WebScraping,另一个用于计时器。一旦计时器达到x分钟,它将发送信号杀死两个线程?