0

我对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() 
4

3 回答 3

0

之后数据不会刷新到磁盘c.writerows(rows)。参考这里

于 2013-04-02T04:03:03.483 回答
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)
于 2013-04-02T04:03:29.110 回答
0

看来您对“with”语句不熟悉,这里有一篇关于它的帖子。

在您的情况下,您可以这样做:

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)    

没有人会难为您,所以请放松并随意提问:)

于 2013-04-02T03:48:34.720 回答