python脚本忽略文件中的换行符
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python脚本忽略文件中的换行符,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2697字,纯文字阅读大概需要4分钟。
内容图文
以下内容位于文件中.我使用shell脚本调用python脚本.此python脚本发送邮件.但是在邮件内容中,我看到如下所示的输出.它们全部在一行中..我在做什么错
/usr/bin/python $DIR/sm.py "$message" "`cat /tmp/alert.txt`"
输入:以下是alert.txt的内容
Thu Jun 28 14:29:26 IST 2012
Disk usage limit exceeded -Current disk usage is 167G-Configured disk usage is 200HTTPD connections exceeded configured usage limit -Current HTTPD connections is 21-Configured HTTPD connection is 20
========================OTHER INFO==================
Total fds: 8
Socket fds: 0
Other fds: 8
Free memory :Free Memory:183732
Buffered memory Buffered Memory:78224
Cache memory : Cache Memory:579040
Disk usage is 167G
DB connections 1
Network connections 21
CPU Usage: 0.0
输出:
Thu Jun 28 14:29:26 IST 2012 Disk usage limit exceeded -Current disk usage is 167G-Configured disk usage is 200HTTPD connections exceeded configured usage limit -Current HTTPD connections is 21-Configured HTTPD connection is 20 ========================OTHER INFO================== Total fds: 8 Socket fds: 0 Other fds: 8 Free memory :Free Memory:183732 Buffered memory Buffered Memory:78224 Cache memory : Cache Memory:579040 Disk usage is 167G DB connections 1 Network connections 21 CPU Usage: 0.0
这是sm.py
import logging
import smtplib
import sys
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
try:
smaid = qs[0].id
gmailUser = 'no-reply@xxxxxxxxxxx.com'
gmailPassword = '12345'
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
to_addr = "xxxxx@xx.com"
subject = sys.argv[1]
body = sys.argv[2]
try:
msg = MIMEMultipart()
msg['From'] = gmailUser
msg['To'] = to_addr
msg["Content-type"] = "text/html"
sub = subject
msg['Subject'] = sub
body = body
msg.attach(MIMEText(body, 'html'))
mailServer.sendmail(gmailUser, to_addr, msg.as_string())
except:
write_exception("send exception")
mailServer.close()
except:
write_exception("send exception1")
解决方法:
如果您坚持发送HTML,则需要HTML换行符:
import cgi
# escape special HTML characters
body = cgi.escape(body)
# use HTML line breaks
body = body.replace("\r\n", "\n").replace("\n", "<br />\n")
但是可能您既不需要Multipart也不需要HTML,因此可以只使用smtplib.SMTP.sendmail:
headers = (('From', gmailUser),
('To', to_addr),
('Subject', subject))
# normalize newlines to CR+LF, as required by SMTP
body = body.replace("\r\n", "\n").replace("\n", "\r\n")
msg = '\r\n'.join("%s: %s" % kv for kv in headers) + '\r\n'*2 + body
mailServer.sendmail(gmailUser, [to_addr], msg)
同样,您不应通过命令行提供文件内容,因为命令行是受长度限制的.相反,您应该通过STDIN提供文件,例如python …< /tmp/alert.txt并通过阅读
import sys
body = sys.stdin.read()
内容总结
以上是互联网集市为您收集整理的python脚本忽略文件中的换行符全部内容,希望文章能够帮你解决python脚本忽略文件中的换行符所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。