尝试,除了不在Python中工作

时间:2017-10-20 15:16:56

标签: python

我正在尝试通过添加try和except块来为此程序添加错误处理,以防某些东西不起作用,以便在处理数据时出现错误时程序不会关闭。 (这是我的代码的一个愚蠢的版本)。当我以这种方式运行时(假设时间准确),似乎没有任何工作 - report_scheduler中的函数实际上并没有运行。

以下是我正在查看的代码:

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()

我理解pass不是错误处理,但我确实需要某种方式告诉程序继续,即使数据没有更新/发生错误。

感谢。

2 个答案:

答案 0 :(得分:2)

如果没有真正深入到您的代码中,可能会引发异常,然后捕获,然后传递语句意味着您没有获得任何输出。

你是否检查过它没有尝试除了块?

此外,这可能会有所帮助:

except Exception as e:
  print("Exception raised: {}".format(e))

至少你会得到你的例外打印件。您可能还想查看记录异常。

答案 1 :(得分:2)

我对你正在使用的图书馆不熟悉 - 如果你发布一个我们可以自己修补的完整程序,并且将所有第三个命名为涉及的派对图书馆 - 但我怀疑你想要 forex_data_reportcompetitor_stock_data_report内的try-except块。您不关心安排定期任务的行为所引发的异常,是吗?您想要从定期任务本身中吞下例外。尝试使用以下结构的代码:

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)

另请注意,我使用except Exception代替except。裸露的except会抓住您几乎肯定不想抓住的内容,例如KeyboardInterruptStopIteration