Python在输出中包含If/else的内容,而不仅仅是prin

2024-04-25 01:49:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python不是很有经验,但是我会为一些小工作编写python代码。目前,我有一个作业,打开一个日志文件,并提取任何被认为是错误的记录。然后将此错误列表添加为电子邮件通知的一部分。我想做的是要么包括列表,要么通知列表为空。我已经能够在控制台中这样做,但不知道如何将其作为参数添加到电子邮件中。你知道吗

if errorlist:
    print "\n".join(errorlist)
else:
    print "No Errors Found"

# Send Email 
SMTP_SERVER = {SMTP SERVER}
SMTP_PORT = {SMTP PORT}

sender = {Sender}
password = {Password}
recipient = {Recipient}
subject = "This is the subject line"
errorlist = "<br>" "\n".join(errorlist)

body = "" + errorlist + ""

headers = ["From: " + sender,
       "Subject: " + subject,
       "To: " + ", " .join(recipient),
       "MIME-Version: 1.0",
       "Content-Type: text/html"]
headers = "\r\n".join(headers)

session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)

session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()

Tags: 列表serverport电子邮件session错误passwordsmtp
2条回答
if errorlist:
    error_string =  "\n".join(errorlist) # assign it to variable
    print (error_string) # still print it
else:
    error_string = "" # assign blank to error_string
    print ("No Errors Found") # still print "no errors found"
    .
    .
    .
    body = ""+error_string+"" # 'body = error_string' is the same though
    .
    .
    .
    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) # this line you could replace "body" with "error_string" because they are pretty much goign to be equivilant because of the previous comment

您希望将错误字符串赋给一个变量,然后在以后构造主体时使用该变量。还有更大的简化空间

电子邮件通过以下行发送:

session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)

body变量包含电子邮件的正文。为了在邮件正文中添加内容,应该将其添加到body变量所包含的字符串中。调整已添加的代码(成功打印所需结果),可以替换此行:

body = "" + errorlist + ""

有了这个:

if errorlist:
    body = "\n".join(errorlist)
else:
    body = "No Errors Found"

相关问题 更多 >