[英]Try, except not working in Python
I am trying to add error handling to this program by adding try and except blocks in case something does not work and so that the program does not shutdown in case there is an error in handling the data. 我试图通过添加try和except块来向该程序添加错误处理,以防万一某些内容无法正常工作,并且在处理数据时出现错误的情况下不会关闭程序。 (This is a dumbed down version of my code).
(这是我的代码的精简版)。 When I run it this way, (given that the time is accurate), nothing seems to work - the functions in
report_scheduler
do not actually ever run. 当我以这种方式运行它时(假设时间是准确的),似乎没有任何效果
report_scheduler
的函数实际上从未运行过。
Here is the code I am looking at: 这是我正在查看的代码:
import schedule
def forex_data_report():
from forex_python.converter import CurrencyRates
import csv
current_dir = os.getcwd()
date_time = time.strftime('%m-%d-%Y_at_%I-%M-%S-%p')
c = CurrencyRates()
usd_eur = c.get_rate('EUR', 'USD')
usd_gbp = c.get_rate('GBP', 'USD')
usd_yen = c.get_rate('JPY', 'USD')
usd_aud = c.get_rate('AUD', 'USD')
eur_gbp = c.get_rate('GBP', 'EUR')
clean_file_location = current_dir + '\\Reports\\Forex_Data\\Forex_Data.csv'
with open(clean_file_location, 'a', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow([date_time, usd_eur, usd_gbp, usd_yen, usd_aud, eur_gbp])
send_outlook_w_attach('Key Currencies', clean_file_location)
print ('Updated Key Currencies Data.')
def competitor_stock_data_report():
import datetime
import pandas_datareader.data as web
import csv
current_dir = os.getcwd()
date_print = time.strftime('%m-%d-%Y_at_%I-%M-%S-%p')
date_time = datetime.datetime.now()
date = date_time.date()
stocklist = ['LAZ','AMG','BEN','LM','EVR','GHL','HLI','MC','PJT','MS','GS','JPM','AB']
start = datetime.datetime(date.year-1, date.month, date.day-1)
end = datetime.datetime(date.year, date.month, date.day-1)
clean_file_location = current_dir + '\\Reports\\XXX\\Stock_Data.csv'
for x in stocklist:
df = web.DataReader(x, 'google', start, end)
with open(clean_file_location, 'a', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow([date_print, x, df.loc[df.index[0], 'Close'], df.loc[df.index[-1], 'Close']])
send_outlook_w_attach('Competitor Stock Data vs. XXX', clean_file_location)
print ('Updated XXX Competitor Stock Performance Data.')
def report_scheduler():
try:
schedule.every().day.at("00:00").do(forex_data_report)
except:
pass
try:
schedule.every().friday.at("00:01").do(competitor_stock_data_report)
except:
pass
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == '__main__':
print('Starting background - HANDLER - process...')
report_scheduler()
I understand the pass
is not error handling, but I do need some sort of way to tell the program to continue, even if the data is not being updated/an error occurs. 我知道该
pass
不是错误处理,但是我确实需要某种方式来告诉程序继续,即使数据没有更新/发生错误也是如此。
Thanks. 谢谢。
Without actually getting deep into your code, probably an exception is being raised and then caught and then the pass statement means you don't get any output. 在没有真正深入代码的情况下,可能会引发异常,然后将其捕获,然后pass语句意味着您不会获得任何输出。
Have you checked it runs without the try except blocks? 您是否检查了它的运行情况,但没有尝试使用try块?
Also, this might help: 此外,这可能会有所帮助:
except Exception as e:
print("Exception raised: {}".format(e))
At least then you will get a printout of your exception. 至少您会获得例外打印输出。 You might also want to look into logging the exception.
您可能还想研究记录异常。
I'm not familiar with the libraries you are using - it would be very helpful if you would post a complete program that we could tinker with ourselves, and name all of the third-party libraries involved - but I suspect you want the try-except blocks inside forex_data_report
and competitor_stock_data_report
. 我对您使用的库不熟悉-如果您发布一个我们可以自行完善的完整程序并命名所有涉及的第三方库,这将非常有帮助-但我怀疑您想要尝试-除了内部块
forex_data_report
和competitor_stock_data_report
。 You aren't concerned with exceptions thrown by the act of scheduling the periodic task , are you? 您不关心调度定期任务的行为引发的异常,是吗? You want to swallow exceptions from the periodic tasks themselves .
您想吞并定期任务本身中的异常。 Experiment with code structured like this:
试用结构如下的代码:
def forex_data_report():
# unchanged
def forex_data_report_wrapper():
try:
forex_data_report()
except Exception as e:
logger.exception(e)
# similarly for competitor_stock_data_report
def report_scheduler():
schedule.every().day.at("00:00").do(forex_data_report_wrapper)
schedule.every().friday.at("00:01").do(competitor_stock_data_report_wrapper)
while True:
schedule.run_pending()
time.sleep(1)
Note also that I am using except Exception
instead of except
. 另请注意,我正在使用
except Exception
而不是except
。 A bare except
catches things you almost certainly don't want to catch, such as KeyboardInterrupt
and StopIteration
. 几乎没有
except
东西可以捕获您几乎肯定不想捕获的东西,例如KeyboardInterrupt
和StopIteration
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.