gpt4 book ai didi

python - 使用IF处理Python错误

转载 作者:行者123 更新时间:2023-12-03 08:31:06 24 4
gpt4 key购买 nike

我有一个python函数getstock(),它从Yahoo提取随机公司的市场数据进行分析。有时,在脚本中的某个特定点,如果我的函数进入了Yahoo Finance无法识别的公司,则会出现以下错误:

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()函数。”

最佳答案

通常,我会这样做:

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

关于python - 使用IF处理Python错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23360105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com