0

I am very new to python programming, please go easy on me!

I am querying my MySQL database and writing output to a file and sending an email of the results. However the email is being sent before the file is written to. How do I tell my code to do the query and writing to file before sending the email?

#!/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() 
  • Why are you writing out the rows to the disk at all? Seems like you could use an [`io.StringIO`](http://docs.python.org/3/library/io.html#io.StringIO) for storing the query results. – millimoose Apr 02 '13 at 03:06

3 Answers3

0

It seems like you are not familiar with the "with" statement, here is a post about it.

In your case, you can do like this:

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)    

no one will be hard to you, so just relax and be free to ask:)

Roger Liu
  • 1,768
  • 3
  • 16
  • 25
  • Thank you very much Roger, sounds like a plan. Back to the books. –  Apr 03 '13 at 06:56
  • If you like my answer, you can accept it, just click the check mark below the votes,thanks:) – Roger Liu Apr 03 '13 at 07:11
  • I get the following with your code: ` File "./mail.py", line 25, in with query_database_and_mail() as con: AttributeError: query_database_and_mail instance has no attribute '__exit__'` –  Apr 03 '13 at 22:58
  • Aha, there is a typo here, you should write def __exit__(self):, sorry, it's my mistake – Roger Liu Apr 05 '13 at 15:02
  • Making that change yields another error:[code]Traceback (most recent call last): File "./mail.py", line 30, in c.writerows(rows) TypeError: __exit__() takes exactly 1 argument (4 given)[/code] What are the four arguments? I can't post all my code because the system says too long by 522 characters! How do I make code show in a comment? I'm ready to give up here. –  Apr 06 '13 at 03:10
  • well, you can edit your question by adding your code in the question – Roger Liu Apr 06 '13 at 06:49
  • I said I can't post all my code because this system says it's too long by 522 characters! How do I make code show in a comment? I tried [code][/code] but that doesn't seem to work nor does ``. –  Apr 06 '13 at 09:24
  • you needn't post your code in this commit, but in your posted question above,just edit it and post your code. – Roger Liu Apr 06 '13 at 14:44
0

The data is not flushed to disk after c.writerows(rows). Refer here

Community
  • 1
  • 1
Veerabahu
  • 41
  • 3
0

Your problem stems from the fact that when you do an anonymous open, like this:

c = csv.writer(open('/home/pi/mail.csv','wb'))

Python will close the open file when the program ends, and that's when it appears as if its actually written to the disk.

To solve the problem, open the file using the with statement, which will close the file automatically for you:

with open('/home/pi/mail.csv','w') as the_file:
    c = csv.writer(the_file)
    c.writerows(rows)
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284