gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:21 25 4
gpt4 key购买 nike

我有一个 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()

关于python - Exception 连续出现一个多小时后发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32123006/

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