【问题标题】:Python freezes during for loopPython 在 for 循环期间冻结
【发布时间】:2019-12-06 14:38:51
【问题描述】:
def get_price_history_data(ticker):
    pricelist = []
    try:
        pricedata = False
        tradingdays = 252
        Historical_Prices = pdr.get_data_yahoo(symbols=ticker, start=(datetime.today()-timedelta(tradingdays)), end=(datetime.today()))#-timedelta(years4-1)))
        price_df = pd.DataFrame(Historical_Prices)
        pricelist = price_df['Adj Close']
        pricedata = True
    except:
        print(ticker,' failed to get price data')
    return(pricelist, pricedata)

tickers = ['FB','V']

for ticker in tickers:
 [pricelist, pricedata] = get_price_data(ticker)

我有几千个代码列表,我通过这个 for 循环运行。它输出一个单列 df 和一个布尔值。总的来说,它工作得很好,可以满足我的需要。但是,它不一致地无限期冻结,没有错误消息并停止运行,迫使我关闭程序并从头开始重新运行。 如果经过一定时间,我正在寻找一种方法让我跳过 for 循环的迭代。我已经研究了 time.sleep() 和 continue 函数,但无法弄清楚如何将它应用于这个特定的应用程序。如果它冻结,它会冻结在“pdr.get_data_yahoo() 部分”。不胜感激

【问题讨论】:

    标签: python loops exit freeze continue


    【解决方案1】:

    我猜get_data_yahoo() 可能会冻结,因为它正在向服务器发出某种从未得到答复的请求。它没有超时选项,因此最明显的选择是在另一个线程/进程中启动它,如果花费太长时间则终止它。您可以为此使用concurrent.futures。如果您对以下代码的工作方式感到满意,您可以将 sleeps_for_a_while 替换为 get_price_history_data 并将 (3, 1, 4, 0) 替换为 tickers

    from concurrent.futures import ThreadPoolExecutor, TimeoutError
    from time import sleep
    
    TIMEOUT = 2  # seconds
    
    
    def sleeps_for_a_while(sleep_for):
        print('starting {}s sleep'.format(sleep_for))
        sleep(sleep_for)
        print('finished {}s sleep'.format(sleep_for))
    
        # return a value to break out of the while loop
        return sleep_for * 100
    
    
    if __name__ == '__main__':
    
        # this only works with functions that return values
        results = []
        for sleep_secs in (3, 1, 4, 0):
            with ThreadPoolExecutor(max_workers=1) as executor:
                # a future represents something that will be done
                future = executor.submit(sleeps_for_a_while, sleep_secs)
                try:
                    # result() raises an error if it times out
                    results.append(future.result(TIMEOUT))
                except TimeoutError as e:
                    print('Function timed out')
                    results.append(None)
    
        print('Got results:', results)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-06
      • 2014-01-15
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2011-03-12
      • 2015-06-05
      • 1970-01-01
      相关资源
      最近更新 更多