我對python編程非常陌生,請在我身上輕鬆一下!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'] = '[email protected]'
msg['To'] = '[email protected]'
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('smtp.me.com')
s.sendmail('[email protected]','[email protected]', msg.as_string())
s.quit()
?似乎可以使用['io.StringIO'](http://docs.python.org/3/library/io.html#io.StringIO)來存儲查詢結果。 – millimoose