从脚本中将 python 控制台输出作为电子邮件发送的最佳方式是什么?

What is the best way to send python console output as email from within the script?

我有一个 python 脚本可以执行多项操作并在控制台上打印日志。目前,我还没有使用任何日志记录机制(我只是使用 print 打印所需的消息)如何获取所有打印件并将其作为电子邮件发送出去?我是否必须将其全部保存在一个变量中并将其传递给 smtplib?或者有更好的方法吗?

示例代码

for job in fetch.getJobStats():
        if job['userName']+"_"+job['tenantId'] in summaryTotal:
            summary = summaryTotal[job['userName']+"_"+job['tenantId']]
        else:
            summary = Summary(job['userName'], job['tenantId'])
            summaryTotal[summary.user+"_"+summary.tenant] = summary

        summary.jobs.append(Job(job['jobId'], job['jobStatus'], int(job['fileSize'])))
        totalBw += int(job['fileSize'])

    print("Cumulative Size: " + str(totalBw))
    for summaryKey in summaryTotal.keys():
        summary = summaryTotal[summaryKey]

        inprogress = []
        failed = []
        completed = []
        cancelled = []
        totalBwTenantUser = 0

        for job in summary.jobs:
            totalBwTenantUser += job.filesize
            if job.status == "JOBCANCELLED":
                cancelled.append(job.id)
            elif job.status == "JOBCOMPLETED":
                completed.append(job.id)
            elif job.status == "INPROGRESS":
                completed.append(job.id)
            elif job.status == "JOBFAILED":
                completed.append(job.id)

        print("-" * 50)
        print("Tenant: " + summary.tenant)
        print("User  : " + summary.user)
        print("Size    : " + str(totalBwTenantUser))
        print("\n")
        print("INPROGRESS: " + str(inprogress))
        print("COMPLETED : " + str(completed))
        print("CANCELLED : " + str(cancelled))
        print("FAILED    : " + str(failed))
        print("-" * 50)

所有打印件都应通过电子邮件拍摄。

你真的应该使用 Python 附带的优秀 logging system

将它与 mailinglogger 处理程序结合起来,您就拥有了所需的一切:

import logging

from mailinglogger.SummarisingLogger import SummarisingLogger

handler = SummarisingLogger('from@example.com',
                            ('to@example.com',),
                            subject='[LOGS] %s (hostname)s',
                            mailhost='smtp.example.com')

logging.basicConfig(format='%(asctime)s %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p',
                    level=logging.INFO)
logger = logging.getLogger()
logger.addHandler(handler)

logging.info('Sent by email.')

我会使用 logging library, configure the logging to a file then just read the contents of that file and send it or attach the log file directly to the email you're sending (see How to send email attachments with Python).