2014-04-29 27 views
0

我有一個python函數getstock(),它爲雅虎隨機公司提供市場數據進行分析。偶爾,在腳本中一個特定的點,如果我的功能一個公司進入雅虎財經不承認,我會收到以下錯誤:使用IF處理Python時出錯

Traceback (most recent call last): 
    File "<pyshell#65>", line 8, in <module> 
    stockhistory=pandas.io.data.get_data_yahoo(stock, start=datetime(1900,1,1), end=datetime(2014,1,1)) 
    File "/usr/lib/python2.7/dist-packages/pandas/io/data.py", line 405, in get_data_yahoo 
    adjust_price, ret_index, chunksize, 'yahoo', name) 
    File "/usr/lib/python2.7/dist-packages/pandas/io/data.py", line 351, in _get_data_from 
    hist_data = src_fn(symbols, start, end, retry_count, pause) 
    File "/usr/lib/python2.7/dist-packages/pandas/io/data.py", line 200, in _get_hist_yahoo 
    return _retry_read_url(url, retry_count, pause, 'Yahoo!') 
    File "/usr/lib/python2.7/dist-packages/pandas/io/data.py", line 177, in _retry_read_url 
    "return a 200 for url %r" % (retry_count, name, url)) 
IOError: after 3 tries, Yahoo! did not return a 200 for url 'http://ichart.finance.yahoo.com/table.csv?s=LE&a=0&b=1&c=1900&d=0&e=1&f=2014&g=d&ignore=.csv' 

這可以通過只使用一個不同的公司進行補救(再次調用該函數)。

我的問題是:我該如何編寫一個if語句來有效地表示「如果發生上述錯誤,請再次運行函數getstock()」。

回答

1

一般來說,我會做這樣的:

for stock in stocks: 
    try: 
     stockhistory = pandas.io.data.get_data_yahoo(stock, ...) 
    except IOError: 
     pass # it failed, skip on to next stock in stocks 
    else: 
     # it succeeded, process stockhistory here