Skip to main content
 首页 » 编程设计

python之Exception 连续出现一个多小时后发送邮件

2025年05月04日28softidea

我有一个 Python 程序,它每 5 分钟从一个 cron 作业中处理一个带有 Selenium 的网页。 cron 向我发送每个引发的异常的电子邮件(cron 只捕获所有 stderr)。有时网站有一些持续的内部错误,我最终会收到数百封系统电子邮件来检查。然后我开始忽略异常,但我发现如果问题持续一小时程序会给我发送电子邮件会更理智。

我写了下面的代码:

#!/usr/bin/env python3 
 
import sys, os, time 
 
name = os.path.basename(sys.argv[0]) 
 
def send_email(server, message): 
    # just print for testing 
    print('Sending email...') 
 
def handle_exception(exception, function): 
    # save a state file in /dev/shm with the name of the exception 
    warn_state = '/dev/shm/{}.{}'.format(name, exception.__name__) 
    try: 
        function 
    except(exception) as exception: 
        if os.path.exists(warn_state): 
            if time.time() - os.path.getmtime(warn_state) > 3600: 
                send_email('localhost', exception.args[1]) 
        else: 
            open(warn_state, 'w').close() 
    else: 
        if os.path.exists(warn_state): 
            os.remove(warn_state) 
 
def my_function(): 
    # try raising a NameError 
    print(undefined_variable) 
 
# run my_function() catching exceptions 
handle_exception(NameError, my_function) 

当我运行上面的代码时,我检查了 else: 部分正在执行,表明 function 根本没有失败。我是编程新手,所以我真的不知道这是否是正确的方法,但我创建了这个函数,因为我必须处理这个脚本中至少五种不同类型的异常,这些异常被引发由于服务器或网络问题,由 Selenium 随机生成。

请您参考如下方法:

你实际上并没有调用函数

function 

什么都不做。你需要做的

function()