忽略Python多行字符串中的变量

时间:2018-04-13 10:05:13

标签: python

我使用Python脚本转发HTML电子邮件,该脚本位于多行字符串中。它需要读取4个外部给定的变量(哪个有效)。但是有一封邮件:链接哪个使用%20和%40。我使用%s来引用其他对象。当我尝试执行脚本时,它会出现以下错误:

  

TypeError:%o format:需要一个数字,而不是str

我理解,因为它期望%20和%40也是对变量的引用。我真的想要包含邮件:链接,但我似乎无法让Python忽略这些值。

#!/usr/bin/env python

list1=[0,1,2,3,4];

import mimetypes, os, smtplib, sys, 
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
from email.utils import make_msgid


me = "xx@yy.nl"
you = "yy@xx.nl"
DESTINATION=sys.argv[1]
SUBJECT=sys.argv[2]
MESSAGE=sys.argv[3]
PASS='password'
SRVSMTP='mysmtpserv:587'
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = me
msg['To'] = you
msg['Date'] = formatdate()
msg['Message-ID'] = make_msgid()

sys.argv[3].split(";")
hostnam, trgname, trgstat, trgseve = sys.argv[3].split(";")
print sys.argv[3].split(";")

text = """ plaintext email here
"""
html = """
<html>
<head>
        <title></title>
</head>
<body>
<p style="margin-left: 80px;"><strong>Trigger:</strong> %s trgname <br />
<strong>Status</strong>: %s  trgstat <br />
<strong>Severity:</strong> %s  trgseve </p>

<p style="margin-left: 40px;"><a href="mailto:xx%40yy.nl?bcc=yy%40xx.com&amp;body=insert%20text%2C%0A%0Ahere%20for%20the%20emailA%5BFirmname%5D%0A%5B%28Address%29%20Adressline2%5D">Click here</a> &nbsp;<strong> %s hostnam.</strong><br />
&nbsp;</p>
<a href="mailto:xxxyyy@yxy.com?subject=Unsubscribe%20me">Click here to unsubscribe</a>&nbsp;</span><br />
&nbsp;</p>
</body>
</html>
""" % ('hostnam', 'trgname', 'trgstat', 'trgseve', 'hostnam')

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
smtpserver = smtplib.SMTP(SRVSMTP)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(me, PASS)
smtpserver.sendmail(me, you, msg.as_string())
smtpserver.quit()

3 个答案:

答案 0 :(得分:2)

您可以使用format来代替您当前使用的%

在您的示例中,将所有%s替换为{},然后将% ('hostnam', 'trgname', 'trgstat', 'trgseve', 'hostnam')替换为.format(hostnam, trgname, trgstat, trgseve, hostnam)

答案 1 :(得分:2)

template strings怎么样?

from string import Template

print(Template("here be %20 %40 my ${placeholder}string").safe_substitute(placeholder="amazing"))

# here be %20 %40 my amazing string

自Python 2.4起可用

答案 2 :(得分:2)

您可以通过加倍来转义不需要的%字符:

<p style="margin-left: 40px;"><a href="mailto:xx%%40yy.nl?bcc=yy%%40xx.com&amp;body=insert%%20text%%2C%%0A%%0Ahere%%20for%%20the%%20emailA%%5BFirmname%%5D%%0A%%5B%%28Address%%29%%20Adressline2%%5D">Click here</a> &nbsp;<strong> %s hostnam.</strong><br />

这有点单调乏味,其他答案可能更好;我只是提到完整性。