<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: python code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 25 Jul 2008 22:43:33 GMT</pubDate>
    <description>DZone Snippets: python code</description>
    <item>
      <title>Making md5sum.exe Work with Paths in Python</title>
      <link>http://snippets.dzone.com/posts/show/4139</link>
      <description>On Windows systems, md5sum.exe is a nice little program to generate MD5 sums. However, whoever created this application forgot to add the ability to recognize paths in the file given to md5sum.exe. For example, say you want to md5 a file called test.txt.&lt;br /&gt;&lt;br /&gt;C:\test&gt;dir&lt;br /&gt; Directory of C:\test&lt;br /&gt;&lt;br /&gt;06/13/2007  03:52 PM    &lt;DIR&gt;          .&lt;br /&gt;06/13/2007  03:52 PM    &lt;DIR&gt;          ..&lt;br /&gt;06/13/2007  03:52 PM                 0 test.txt&lt;br /&gt;               1 File(s)              0 bytes&lt;br /&gt;&lt;br /&gt;C:\test&gt;md5sum test.txt&lt;br /&gt;d41d8cd98f00b204e9800998ecf8427e *test.txt&lt;br /&gt;&lt;br /&gt;Groovy, cool...&lt;br /&gt;&lt;br /&gt;However, if you try the same thing from some other directory (where text.txt does not live) you get the following:&lt;br /&gt;&lt;br /&gt;C:\&gt;md5sum c:/test/test.txt&lt;br /&gt;md5sum: test.txt: No such file or directory&lt;br /&gt;&lt;br /&gt;Sucky, eh?&lt;br /&gt;You could always find a different program to do md5sum. Or, if you don't want to do this, you can spawn a pipe to "cmd", navigate to the correct directory, and then run md5sum.&lt;br /&gt;&lt;br /&gt;Here's the code in python to do just that.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# define your file name and path&lt;br /&gt;file_name = "afile.txt"&lt;br /&gt;file_path = "c:\\afolder"&lt;br /&gt;&lt;br /&gt;# setup the md5sum command (assuming md5sum.exe location is in PATH)&lt;br /&gt;md5_cmd = "md5sum \"" + file_path "\\" + file_name + "\"\n"&lt;br /&gt;&lt;br /&gt;# open the command shell&lt;br /&gt;fromchild, tochild = popen2.popen4("cmd")&lt;br /&gt;&lt;br /&gt;#push the directory change and md5sum commands to the shell &lt;br /&gt;tochild.write("c:\nchdir " + my_path + "\n" + md5_cmd + "exit\n")&lt;br /&gt;tochild.close()&lt;br /&gt;&lt;br /&gt;#get the output from the shell session&lt;br /&gt;out = fromchild.read()&lt;br /&gt;&lt;br /&gt;#split the output so that we may extract the md5sum&lt;br /&gt;output = string.split(out)&lt;br /&gt;&lt;br /&gt;#grab the md5sum  &lt;br /&gt;md5sum_local = ""&lt;br /&gt;for item in output:&lt;br /&gt;    matchmd5local = re.match("([0-9a-fA-F]{32})",item)&lt;br /&gt;    if matchmd5local:&lt;br /&gt;        md5sum_local = matchmd5local.groups()&lt;br /&gt;        md5sum_local = md5sum_local[0]&lt;br /&gt;&lt;br /&gt;if md5sum_local:&lt;br /&gt;    print_status("MD5: Local checksum = " + md5sum_local + "\n")&lt;br /&gt;else:&lt;br /&gt;    print_status("ERROR: could not obtain local md5sum for " + my_file + "\n")&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 13 Jun 2007 23:10:02 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4139</guid>
      <author>minitotoro (Natalie)</author>
    </item>
    <item>
      <title>Automate Defrag of Windows Host via Python</title>
      <link>http://snippets.dzone.com/posts/show/3925</link>
      <description>Automation script to defrag a Windows machine. The defrag results will be emailed to specified email address. This script can also handle running defrag over multiple volumes. NOTE: if you are running this on Windows 2003 64-bit you have to place a copy of defrag.exe in the same directory as the python script. Otherwise Windows will barf and say it doesn't know what defrag is. Don't know why this happens.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#*****************************************************************#&lt;br /&gt;#                                                                 #&lt;br /&gt;# Filename:             autodefrag.py                             #&lt;br /&gt;# Date Written:         4/27/2007                                 #&lt;br /&gt;#                                                                 #&lt;br /&gt;# Purpose:              Intelligent interface to Windows defrag   #&lt;br /&gt;#                       command. Emails results when complete.    #&lt;br /&gt;#                       Can handle multiple volumes. Add this     #&lt;br /&gt;#                       script to Windows task scheduler to       #&lt;br /&gt;#                       fully automate defragmentation.           #&lt;br /&gt;#                                                                 #&lt;br /&gt;# OS:        		Windows 2003, XP                          #&lt;br /&gt;#                                                                 #&lt;br /&gt;#*****************************************************************#&lt;br /&gt;&lt;br /&gt;import smtplib, sys, MimeWriter, StringIO, base64, os, time&lt;br /&gt;&lt;br /&gt;##VARIABLES########################################################&lt;br /&gt;&lt;br /&gt;drives = ["C:","D:","E:"]           # list of volumes to defragment&lt;br /&gt;SMTP_server = "somemailserver.com"  #SMTP email server&lt;br /&gt;email_to = "someone@example.com"   &lt;br /&gt;email_from = "someone2@example.com"&lt;br /&gt;logfile_path = "c:/"               #path to where logfile is saved&lt;br /&gt;&lt;br /&gt;##END_VARIABLES####################################################&lt;br /&gt;&lt;br /&gt;def mail(serverURL=None, sender='', to='', subject='', text=''):&lt;br /&gt;&lt;br /&gt;    message = StringIO.StringIO()&lt;br /&gt;    writer = MimeWriter.MimeWriter(message)&lt;br /&gt;    writer.addheader('Subject', subject)&lt;br /&gt;    writer.startmultipartbody('mixed')&lt;br /&gt;&lt;br /&gt;    # start off with a text/plain part&lt;br /&gt;    part = writer.nextpart()&lt;br /&gt;    body = part.startbody('text/plain')&lt;br /&gt;    body.write(text)&lt;br /&gt;&lt;br /&gt;    # now add an attachment&lt;br /&gt;    part = writer.nextpart()&lt;br /&gt;    part.addheader('Content-Transfer-Encoding', 'base64')&lt;br /&gt;    body = part.startbody('text/plain')&lt;br /&gt;    base64.encode(open(filename, 'rb'), body)&lt;br /&gt;&lt;br /&gt;    # finish off&lt;br /&gt;    writer.lastpart()&lt;br /&gt;&lt;br /&gt;    # send the mail&lt;br /&gt;    smtp = smtplib.SMTP(serverURL)&lt;br /&gt;    smtp.sendmail(sender, to, message.getvalue())&lt;br /&gt;    smtp.quit()&lt;br /&gt;&lt;br /&gt;def timestamp():&lt;br /&gt;    #mytime = time.asctime(time.localtime())&lt;br /&gt;    mytime = time.strftime("%Y%m%d", time.localtime())&lt;br /&gt;    return mytime&lt;br /&gt;&lt;br /&gt;##MAIN#############################################################&lt;br /&gt;#get the host name&lt;br /&gt;hs = os.popen('hostname')&lt;br /&gt;computer_name = hs.read()&lt;br /&gt;hs.close()&lt;br /&gt;&lt;br /&gt;mytime = timestamp()&lt;br /&gt;filename = logfile_path + "DEFRAG" + mytime + ".log"&lt;br /&gt;&lt;br /&gt;#execute the defrag command for each drive&lt;br /&gt;for d in drives:&lt;br /&gt;    cmd = "defrag.exe -v " + d + " &gt;&gt;" + filename&lt;br /&gt;    print "Starting defragment: ", cmd&lt;br /&gt;    errorlevel = os.system(cmd)&lt;br /&gt;    if errorlevel == 0:&lt;br /&gt;        print "Emailing results"&lt;br /&gt;        mail(SMTP_server,email_from,email_to,'Disk Defrag of ' + computer_name + ' Complete','Disk defragmentation finished\n')&lt;br /&gt;    else:&lt;br /&gt;        print "Error occurred! Emailing results"&lt;br /&gt;        mail(SMTP_server,email_from,email_to,'Disk Defrag of ' + computer_name + ' Error','Disk defragmentation encountered an error')&lt;br /&gt;&lt;br /&gt;        #hold the cmd window open if error occurred - remove this if you want window to exit&lt;br /&gt;        hold = raw_input('\nPress ENTER to exit')&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 27 Apr 2007 17:00:08 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3925</guid>
      <author>minitotoro (Natalie)</author>
    </item>
    <item>
      <title>Send Email in Python with Text File Attachment</title>
      <link>http://snippets.dzone.com/posts/show/3910</link>
      <description>// description of your code here&lt;br /&gt;Send an email in python with a text attachment. You can change the attachment type by adjusting the part.startbody label in the attachment section (ie, 'image/jpg' or whatever)&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;import smtplib, sys, MimeWriter, StringIO, base64&lt;br /&gt;import os&lt;br /&gt;def mail(serverURL=None, sender='', to='', subject='', text=''):&lt;br /&gt;    """&lt;br /&gt;    Usage:&lt;br /&gt;    mail('somemailserver.com', 'me@example.com', 'someone@example.com', 'test', 'This is a test')&lt;br /&gt;    """&lt;br /&gt;    message = StringIO.StringIO()&lt;br /&gt;    writer = MimeWriter.MimeWriter(message)&lt;br /&gt;    writer.addheader('Subject', subject)&lt;br /&gt;    writer.startmultipartbody('mixed')&lt;br /&gt;&lt;br /&gt;    # start off with a text/plain part&lt;br /&gt;    part = writer.nextpart()&lt;br /&gt;    body = part.startbody('text/plain')&lt;br /&gt;    body.write(text)&lt;br /&gt;&lt;br /&gt;    # now add an attachment&lt;br /&gt;    part = writer.nextpart()&lt;br /&gt;    part.addheader('Content-Transfer-Encoding', 'base64')&lt;br /&gt;    body = part.startbody('text/plain')&lt;br /&gt;    base64.encode(open('myfile.txt', 'rb'), body)&lt;br /&gt;&lt;br /&gt;    # finish off&lt;br /&gt;    writer.lastpart()&lt;br /&gt;&lt;br /&gt;    # send the mail&lt;br /&gt;    smtp = smtplib.SMTP(serverURL)&lt;br /&gt;    smtp.sendmail(sender, to, message.getvalue())&lt;br /&gt;    smtp.quit()&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 26 Apr 2007 17:23:42 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3910</guid>
      <author>minitotoro (Natalie)</author>
    </item>
    <item>
      <title>Send an Email from Python</title>
      <link>http://snippets.dzone.com/posts/show/3909</link>
      <description>// description of your code here&lt;br /&gt;Not sure where I got this from, but it does its job. Sends a simple smtp email message in python.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;import smtplib&lt;br /&gt;def mail(serverURL=None, sender='', to='', subject='', text=''):&lt;br /&gt;    """&lt;br /&gt;    Usage:&lt;br /&gt;    mail('somemailserver.com', 'me@example.com', 'someone@example.com', 'test', 'This is a test')&lt;br /&gt;    """&lt;br /&gt;    headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to, subject)&lt;br /&gt;    message = headers + text&lt;br /&gt;    mailServer = smtplib.SMTP(serverURL)&lt;br /&gt;    mailServer.sendmail(sender, to, message)&lt;br /&gt;    mailServer.quit()&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 26 Apr 2007 16:24:34 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3909</guid>
      <author>minitotoro (Natalie)</author>
    </item>
  </channel>
</rss>
