我每 10 分钟运行一个 python 脚本 (crontab),它会监视正常运行时间,以警告我任何重新启动的情况。 如果重新启动,它会向我发送一封电子邮件。有一个 python 电子邮件脚本,当重新启动并发送电子邮件( smtplib )时我会调用它。当我手动运行主脚本时,一切都按预期进行。电子邮件已发送。当我以用户身份每 10 分钟运行一次 crontab 时,电子邮件不会发送。我在 Ubuntu 中运行该脚本。代码如下:
from subprocess import call
from datetime import date
import psutil
import time
import datetime
td = datetime.datetime.now()
today = td.strftime('%Y-%m-%d-%H:%M')
logpath1 = '/home/jim/usb/logs/uptime_boot.log'
logpath2 = '/home/jim/usb/logs/uptime.log'
def seconds_elapsed():
return time.time() - psutil.boot_time()
uptime = seconds_elapsed()
optime = str(int(uptime))
if uptime < 660:
#print("There was a reboot: "+ today )
with open(logpath1, "a") as file1:
#Writing data to a file
file1.write("Reboot < 11 min ago: "+ today+"\n")
call(["/usr/bin/python3","/home/jim/usb/pythons/send_epost1.py"])
if uptime > 660:
#print("No reboot: "+ today )
with open(logpath2, "a") as file1:
#Writing data to a file
file1.write("No reboot yet: "+ today+" Uptime: "+optime+" secs."+"\n")
可能
call()
函数抛出异常。
将异常记录到日志文件中,以便您可以看到它:
with open(logpath1, "a") as file1:
#Writing data to a file
file1.write("Reboot < 11 min ago: "+ today+"\n")
try:
call(["/usr/bin/python3","/home/jim/usb/pythons/send_epost1.py"])
except Exception as ex:
file1.write(f"Caught exception: {ex}")