python格式化输出作业_Python脚本作为cron作业-如何将输出格式化为带有附件的电子邮件?...

#!/usr/bin/pythonfromemail.mime.multipartimportMIMEMultipartfromemail.mime.textimportMIMETextfromemail.mime.baseimportMIMEBasefromemailimportencodersimportsysimportStringIOimportatexit# Back up stdout and stderr. We'll overwrite them by StringIO to save the# output to a string.stdout_copy=sys.stdout

stderr_copy=sys.stderr

f=StringIO.StringIO()sys.stdout=f

sys.stderr=f# The MIME message we're going to wrap the program's output in.msg=MIMEMultipart()# This is the boundary I set in my crontab file. Kludgy, but I knew no other# way to send multipart files from cron. To reproduce it, add the following# to your crontab:## CONTENT_TYPE='multipart/mixed; boundary="------------040907050602020300000601"'msg.set_boundary('------------040907050602020300000601')# At exit, print f's contents as a MIME message.defflush_f():# Rewind the f StringIO so that f.read() will read all the data.f.seek(0)# Restore stdout and stderr - this will let us print to the program's# standard output. Note that we overwrite stderr with the stdout - this# will let us see the error messages in crontab e-mails.sys.stdout=stdout_copy

sys.stderr=stdout_copy# Add the stdout contents to the message body.stdout_contents=MIMEText(f.read(),"plain")msg.attach(stdout_contents)# Attach the attachments. We use "unknown" to trick Thunderbird into# thinking that the file is binary.forfilenameinfilenames:iffilename.endswith(".png"):attachment=MIMEBase("image","png")else:attachment=MIMEBase("application","unknown")attachment.set_payload(open(filename).read())attachment.add_header('Content-Disposition','attachment',filename=filename)encoders.encode_base64(attachment)msg.attach(attachment)# Print the final message.print(msg.as_string())atexit.register(flush_f)print("Hello, world!")filenames=["/etc/redhat-release"]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值