我是python编程的新手,请放轻松我吧!
我正在查询我的MySQL数据库并将输出写入文件并发送结果的电子邮件。但是,在写入文件之前会发送电子邮件。如何在发送电子邮件之前告诉我的代码执行查询并写入文件?
#!/usr/bin/python
# Import smtplib for the actual sending function
import smtplib
import MySQLdb as mdb
import sys
import csv
con = mdb.connect('localhost', 'myuser', 'mypassword', 'mydatabase');
with con:
cur = con.cursor()
cur.execute("SELECT * from vw_mail")
rows = cur.fetchall()
c = csv.writer(open('/home/pi/mail.csv','wb'))
c.writerows(rows)
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open('/home/pi/mail.csv','rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'MySubject'
msg['From'] = 'me@me.com'
msg['To'] = 'you@you.com'
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('smtp.me.com')
s.sendmail('me@me.com','you@you.com', msg.as_string())
s.quit()
答案 0 :(得分:0)
您似乎不熟悉“with”语句,here是关于它的帖子。
在您的情况下,您可以这样做:
class query_database_and_mail:
def __enter__(self):
con = mdb.connect('localhost', 'myuser', 'mypassword', 'mydatabase');
return con
def __exit__(self):
#put your send-email codes here
with query_database_and_email() as con:
cur = con.cursor()
cur.execute("SELECT * from vw_mail")
rows = cur.fetchall()
c = csv.writer(open('/home/pi/mail.csv','wb'))
c.writerows(rows)
没有人会对你很难,所以请放松并随意提问:)
答案 1 :(得分:0)
c.writerows(rows)
后数据不会刷新到磁盘。请参阅here
答案 2 :(得分:0)
您的问题源于这样一个事实:当您进行匿名打开时,请执行以下操作:
c = csv.writer(open('/home/pi/mail.csv','wb'))
当程序结束时,Python将关闭打开的文件,就好像它实际上写入磁盘一样。
要解决此问题,请使用with statement
打开文件,这将自动为您关闭文件:
with open('/home/pi/mail.csv','w') as the_file:
c = csv.writer(the_file)
c.writerows(rows)