Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Natalie http://www.thefuzzyslug.com

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Interactive Text-to-Speech (Windows, Perl)

This script calls the Windows OLE for the built in TTS. Type what you want the computer to say at the prompt and hit enter. To quit type ":q" (minus the quotation marks).


use Win32::OLE qw( EVENTS );

get_text();

sub get_text{
	$output_speech = <STDIN>;
	chomp($output_speech);
	if($output_speech ne ":q"){
		say_this();
		get_text();
	}
}

sub say_this{
	my $myTTS = new Win32::OLE( "Sapi.SpVoice" ); 
	$myTTS->Speak( "$output_speech" );
	while( $myTTS->{Speaking} )
	{
		Win32::OLE->SpinMessageLoop();
		Win32::Sleep( 100 );
	}
}

Making md5sum.exe Work with Paths in Python

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.

C:\test>dir
Directory of C:\test

06/13/2007 03:52 PM <DIR> .
06/13/2007 03:52 PM <DIR> ..
06/13/2007 03:52 PM 0 test.txt
1 File(s) 0 bytes

C:\test>md5sum test.txt
d41d8cd98f00b204e9800998ecf8427e *test.txt

Groovy, cool...

However, if you try the same thing from some other directory (where text.txt does not live) you get the following:

C:\>md5sum c:/test/test.txt
md5sum: test.txt: No such file or directory

Sucky, eh?
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.

Here's the code in python to do just that.

# define your file name and path
file_name = "afile.txt"
file_path = "c:\\afolder"

# setup the md5sum command (assuming md5sum.exe location is in PATH)
md5_cmd = "md5sum \"" + file_path "\\" + file_name + "\"\n"

# open the command shell
fromchild, tochild = popen2.popen4("cmd")

#push the directory change and md5sum commands to the shell 
tochild.write("c:\nchdir " + my_path + "\n" + md5_cmd + "exit\n")
tochild.close()

#get the output from the shell session
out = fromchild.read()

#split the output so that we may extract the md5sum
output = string.split(out)

#grab the md5sum  
md5sum_local = ""
for item in output:
    matchmd5local = re.match("([0-9a-fA-F]{32})",item)
    if matchmd5local:
        md5sum_local = matchmd5local.groups()
        md5sum_local = md5sum_local[0]

if md5sum_local:
    print_status("MD5: Local checksum = " + md5sum_local + "\n")
else:
    print_status("ERROR: could not obtain local md5sum for " + my_file + "\n")

Automate Defrag of Windows Host via Python

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.

#*****************************************************************#
#                                                                 #
# Filename:             autodefrag.py                             #
# Date Written:         4/27/2007                                 #
#                                                                 #
# Purpose:              Intelligent interface to Windows defrag   #
#                       command. Emails results when complete.    #
#                       Can handle multiple volumes. Add this     #
#                       script to Windows task scheduler to       #
#                       fully automate defragmentation.           #
#                                                                 #
# OS:        		Windows 2003, XP                          #
#                                                                 #
#*****************************************************************#

import smtplib, sys, MimeWriter, StringIO, base64, os, time

##VARIABLES########################################################

drives = ["C:","D:","E:"]           # list of volumes to defragment
SMTP_server = "somemailserver.com"  #SMTP email server
email_to = "someone@example.com"   
email_from = "someone2@example.com"
logfile_path = "c:/"               #path to where logfile is saved

##END_VARIABLES####################################################

def mail(serverURL=None, sender='', to='', subject='', text=''):

    message = StringIO.StringIO()
    writer = MimeWriter.MimeWriter(message)
    writer.addheader('Subject', subject)
    writer.startmultipartbody('mixed')

    # start off with a text/plain part
    part = writer.nextpart()
    body = part.startbody('text/plain')
    body.write(text)

    # now add an attachment
    part = writer.nextpart()
    part.addheader('Content-Transfer-Encoding', 'base64')
    body = part.startbody('text/plain')
    base64.encode(open(filename, 'rb'), body)

    # finish off
    writer.lastpart()

    # send the mail
    smtp = smtplib.SMTP(serverURL)
    smtp.sendmail(sender, to, message.getvalue())
    smtp.quit()

def timestamp():
    #mytime = time.asctime(time.localtime())
    mytime = time.strftime("%Y%m%d", time.localtime())
    return mytime

##MAIN#############################################################
#get the host name
hs = os.popen('hostname')
computer_name = hs.read()
hs.close()

mytime = timestamp()
filename = logfile_path + "DEFRAG" + mytime + ".log"

#execute the defrag command for each drive
for d in drives:
    cmd = "defrag.exe -v " + d + " >>" + filename
    print "Starting defragment: ", cmd
    errorlevel = os.system(cmd)
    if errorlevel == 0:
        print "Emailing results"
        mail(SMTP_server,email_from,email_to,'Disk Defrag of ' + computer_name + ' Complete','Disk defragmentation finished\n')
    else:
        print "Error occurred! Emailing results"
        mail(SMTP_server,email_from,email_to,'Disk Defrag of ' + computer_name + ' Error','Disk defragmentation encountered an error')

        #hold the cmd window open if error occurred - remove this if you want window to exit
        hold = raw_input('\nPress ENTER to exit')


« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS