python script to windows exe

S

sandeep

hi all

i am very much a newbie to python but has some experience of
development.i am trying to write a script which will loop through the
outlook 2003 inbox and save the email data in an simple data.html page
and save all the attachments in a folder name emails.after some
initial struggling i am able to write this script.but now i want to
create the exe file of this script.i have used py2exe for this job and
created the exe. but when i run the exe my program in not behaving as
it supposed to be.its generating some errors.i dont know why this
thing is happening as when i run my script it works fine.can some one
put some light here. i am using python2.5 and is using
py2exe-0.6.6.win32-py2.5.exe of py2exe. My os is windows xp with
service pack2.


thanks and reagrds
sandeep kumar sharma
 
E

eglyph

but when i run the exe my program in not behaving as
it supposed to be.its generating some errors.i dont know why this
thing is happening as when i run my script it works fine.can some one
put some light here.

There is nothing special in executables produced by py2exe. I mean
that the debugging strategy is as always. A good start might be in
adding logging\tracing facilities both to script and the executable.
Comparing two trace files could give you some clue.
 
S

sandeep

There is nothing special in executables produced by py2exe. I mean
that the debugging strategy is as always. A good start might be in
adding logging\tracing facilities both to script and the executable.
Comparing two trace files could give you some clue.

hi here is my code.i wont get any errors when i run this script.it may
not be the best pycode as i am very much new to python development.

import win32com,win32com.client
import os,os.path
import codecs
import zipfile

#@Author:::Sandeep Kumar Sharma

#outlook2003 application refrence
outlook_app=0
#outlook ids to access different folders look into msdn for more info.
not a preffered way as i am hardcoding data here
OlDefaultFolders={'olFolderCalendar':9,'olFolderConflicts':
19,'olFolderContacts':10,'olFolderDeletedItems':3,'olFolderDrafts':
16,'olFolderInbox':6,'olFolderJournal':11,'olFolderJunk':
23,'olFolderLocalFailures':21,'olFolderNotes':12,'olFolderOutbox':
4,'olFolderSentMail':5,'olFolderServerFailures':
22,'olFolderSyncIssues':20,'olFolderTasks':
13,'olPublicFoldersAllPublicFolders':18}
#outlook types to save mailItem look into msdn for more info
#although doesnot work for me :-(
OlSaveAsType={'olTXT': 0,'olRTF':1,'olTemplate': 2,'olMSG': 3,'olDoc':
4,'olHTML':5,'olVCard': 6,'olVCal':7,'olICal': 8};

#refrence to content in inbox
inbox_obj=0

#function which will initialise outlook and return its reference
def getAppRef():
temp=win32com.client.Dispatch("OutLook.Application")
return temp.GetNamespace("MAPI")

#function to return the folders in the outlook
def getOutLookFolders(a,b=OlDefaultFolders['olFolderInbox']):
return a.GetDefaultFolder(b)

#function to get email content
def getMailContent(obj):
txt_file=codecs.open('data.html',encoding='utf-8',mode='w')
for kk in range(len(obj.Items),1,-1):
#for kk in range(len(obj.Items-1),0,-1):
#print 'hello'
print 'writting file='+str(kk)
mailItem=obj.Items[kk]
writeData(mailItem,txt_file)

#print mailItem.OlSaveAsType.olMSG
#saveCopy(mailItem)
#print "sender="+mailItem.SenderName+'
SenderEmailId='+str(mailItem.SenderEmailAddress)+'
Time='+str(mailItem.ReceivedTime)
#print 'Subject='+mailItem.Subject+' size='+str(mailItem.Size)

txt_file.close()
'''
file_zip=zipfile.ZipFile(txt_file,"w",zipfile.ZIP_DEFLATED)
file_zip.write('data.log')
file_zip.close()
'''

#function to create a directory
#obviously not a best way :-( but i think can expected this sort of
mistakes from beginners
def createDir():
path=os.path.abspath("\email")
if(os.path.exists(path)):
print "Directory already exists"
else:
os.system("md "+path)

#function to save a copy of email
def writeData(mailItem,file):
data="<p>"
sender='<h4>SenderName</
h4>'+checkStringType(mailItem.SenderName)
time='<br><h4>Time</
h4>'+checkStringType(str(mailItem.ReceivedTime))
attachment='<br><h5>Attachments Count</
h5>'+str(len(mailItem.Attachments))
edata='<h4>Email Content</h4>'+checkStringType(mailItem.Body)+"</
p><hr/>"
dataToWrite=data+sender+time+attachment+edata
getAttachmentInfo(mailItem.Attachments)
file.write(getHTMLString(dataToWrite))
#checkStringType(dataToWrite)

def getAttachmentInfo(atmts):
for kk in range(1,len(atmts)):
atmt=atmts[kk]
#print "File Name="+atmt.FileName+'
DisplayName='+atmt.DisplayName+' PathName='+atmt.PathName+' '
abc=os.path.isdir(os.getcwd()+'\email')

if(abc==True):
print 'directory exists'

else:
os.mkdir(os.getcwd()+'\email')

path=os.path.abspath(os.getcwd()+'\email')
atmt.SaveAsFile(path+"\\"+atmt.DisplayName)



# function to check whether the character encoding is ascii or smthing
else
def checkStringType(a):

if isinstance(a,str):
b='not a unicode string'

else:
a.encode('utf-8')
#print 'unicode type'

return a

#function to save the coopy of an email
#:-( but smhow it generate error whenever i make a call to it
def saveCopy(mailItem):

name="\\"+mailItem.Subject+"__"+str(mailItem.ReceivedTime)
print name
#global outlook_app
try:
mailItem.SaveAs(path+name+".txt",OlSaveAsType['olTXT'])
except BaseException:
print BaseException

def getHTMLString(b):
a='<html><head><title>Your Email Data log is here</title></
head><body>'+b+'</body></html>'
return a

#main entrance to the program
def main():
global outlook_app,inbox_obj
outlook_app=getAppRef()
#print outlook_app.OlSaveAsType.olMSG
print '=================='
print dir(outlook_app)
print '=================='
inbox_obj=getOutLookFolders(outlook_app)
print dir(inbox_obj)
print (inbox_obj.Items)
#saveCopy(inbox_obj.Items[1])
getMailContent(inbox_obj)



main()
 
S

sandeep

hi
the py code that i have written is here.when i run this code i wont
get any errors it just works fine for me.but when i created the exe i
start getting an error in my 'getMailContent' function. The error
description is

TypeError:unsupported operand type(s) for :- 'instance' and 'int'

i dont know why i am start getting this error when i run it through
the exe.


import win32com,win32com.client
import os,os.path
import codecs
import zipfile

#@Author:::Sandeep Kumar Sharma

#outlook application refrence
outlook_app=0
#outlook ids to access different folders look into msdn for more info.
not a preffered way as i am hardcoding data here
OlDefaultFolders={'olFolderCalendar':9,'olFolderConflicts':
19,'olFolderContacts':10,'olFolderDeletedItems':3,'olFolderDrafts':
16,'olFolderInbox':6,'olFolderJournal':11,'olFolderJunk':
23,'olFolderLocalFailures':21,'olFolderNotes':12,'olFolderOutbox':
4,'olFolderSentMail':5,'olFolderServerFailures':
22,'olFolderSyncIssues':20,'olFolderTasks':
13,'olPublicFoldersAllPublicFolders':18}
#outlook types to save mailItem look into msdn for more info
#although doesnot work for me :-(
OlSaveAsType={'olTXT': 0,'olRTF':1,'olTemplate': 2,'olMSG': 3,'olDoc':
4,'olHTML':5,'olVCard': 6,'olVCal':7,'olICal': 8};

#refrence to content in inbox
inbox_obj=0

#function which will initialise outlook and return its reference
def getAppRef():
temp=win32com.client.Dispatch("OutLook.Application")
return temp.GetNamespace("MAPI")

#function to return the folders in the outlook
def getOutLookFolders(a,b=OlDefaultFolders['olFolderInbox']):
return a.GetDefaultFolder(b)

#function to get email content
def getMailContent(obj):
txt_file=codecs.open('data.html',encoding='utf-8',mode='w')
for kk in range(len(obj.Items),1,-1):
#for kk in range(len(obj.Items-1),0,-1):
#print 'hello'
print 'writting file='+str(kk)
mailItem=obj.Items[kk]
writeData(mailItem,txt_file)

#print mailItem.OlSaveAsType.olMSG
#saveCopy(mailItem)
#print "sender="+mailItem.SenderName+'
SenderEmailId='+str(mailItem.SenderEmailAddress)+'
Time='+str(mailItem.ReceivedTime)
#print 'Subject='+mailItem.Subject+' size='+str(mailItem.Size)

txt_file.close()
'''
file_zip=zipfile.ZipFile(txt_file,"w",zipfile.ZIP_DEFLATED)
file_zip.write('data.log')
file_zip.close()
'''

#function to create a directory
#obviously not a best way :-( but i think can expected this sort of
mistakes from beginners
def createDir():
path=os.path.abspath("\email")
if(os.path.exists(path)):
print "Directory already exists"
else:
os.system("md "+path)

#function to save a copy of email
def writeData(mailItem,file):
data="<p>"
sender='<h4>SenderName</
h4>'+checkStringType(mailItem.SenderName)
time='<br><h4>Time</
h4>'+checkStringType(str(mailItem.ReceivedTime))
attachment='<br><h5>Attachments Count</
h5>'+str(len(mailItem.Attachments))
edata='<h4>Email Content</h4>'+checkStringType(mailItem.Body)+"</
p><hr/>"
dataToWrite=data+sender+time+attachment+edata
getAttachmentInfo(mailItem.Attachments)
file.write(getHTMLString(dataToWrite))
#checkStringType(dataToWrite)

def getAttachmentInfo(atmts):
for kk in range(1,len(atmts)):
atmt=atmts[kk]
#print "File Name="+atmt.FileName+'
DisplayName='+atmt.DisplayName+' PathName='+atmt.PathName+' '
abc=os.path.isdir(os.getcwd()+'\email')

if(abc==True):
print 'directory exists'

else:
os.mkdir(os.getcwd()+'\email')

path=os.path.abspath(os.getcwd()+'\email')
atmt.SaveAsFile(path+"\\"+atmt.DisplayName)



# function to check whether the character encoding is ascii or smthing
else
def checkStringType(a):

if isinstance(a,str):
b='not a unicode string'

else:
a.encode('utf-8')
#print 'unicode type'

return a

#function to save the coopy of an email
#:-( but smhow it generate error whenever i make a call to it
def saveCopy(mailItem):

name="\\"+mailItem.Subject+"__"+str(mailItem.ReceivedTime)
print name
#global outlook_app
try:
mailItem.SaveAs(path+name+".txt",OlSaveAsType['olTXT'])
except BaseException:
print BaseException

def getHTMLString(b):
a='<html><head><title>Your Email Data log is here</title></
head><body>'+b+'</body></html>'
return a

#main entrance to the program
def main():
global outlook_app,inbox_obj
outlook_app=getAppRef()
#print outlook_app.OlSaveAsType.olMSG
print '=================='
print dir(outlook_app)
print '=================='
inbox_obj=getOutLookFolders(outlook_app)
print dir(inbox_obj)
print (inbox_obj.Items)
#saveCopy(inbox_obj.Items[1])
getMailContent(inbox_obj)



main()


my setup file has this code

from distutils.core import setup
import py2exe

setup(console=['outlook.py'])


i have just copied and pasted it from the tutorial available at the
py2exe site and changed the filename with mine filename.


thanks and regards
sandeep kumar sharma
 
F

Fuzzyman

hi all

i am very much a newbie to python but has some experience of
development.i am trying to write a script which will loop through the
outlook 2003 inbox and save the email data in an simple data.html page
and save all the attachments in a folder name emails.after some
initial struggling i am able to write this script.but now i want to
create the exe file of this script.i have used py2exe for this job and
created the exe. but when i run the exe my program in not behaving as
it supposed to be.its generating some errors.i dont know why this
thing is happening as when i run my script it works fine.can some one
put some light here. i am using python2.5 and is using
py2exe-0.6.6.win32-py2.5.exe of py2exe. My os is windows xp with
service pack2.

thanks and reagrds
sandeep kumar sharma


You'll need to post the actual errors you get for people to be able to
help. You might find posting to the py2exe mailing list useful.

All the best,


Michael Foord
http://www.ironpythoninaction.com/
 
G

Gabriel Genellina

the py code that i have written is here.when i run this code i wont
get any errors it just works fine for me.but when i created the exe i
start getting an error in my 'getMailContent' function. The error
description is

TypeError:unsupported operand type(s) for :- 'instance' and 'int'

i dont know why i am start getting this error when i run it through
the exe.

By example, your code uses os.getcwd() - so it depends on the current dir. Try running it from a different directory. Don't focus too much on the ".exe" vs ".py" difference: it might not be relevant, the error may reside elsewhere.

Please post the complete exception message *and* traceback. Don't retype it; copy and paste the message from the console. Your message above doesn't appear to be correctly typed, it says `:-` but Python would print `-:` and I don't see any `-` operation in your code that could fail in that way.

Also, don't do this:
try:
mailItem.SaveAs(path+name+".txt",OlSaveAsType['olTXT'])
except BaseException:
print BaseException

because you're completely hiding important information about *what* happened.
 
S

sandeep

hi all

thanks for ur replies. i have a bit closer look at my code and i am
able to fix the problem.now my exe is working fine.the code is bit
more cleaner now as i removed lot of unused function from it and try
to document it also.


import win32com,win32com.client
import os,os.path
import codecs
import zipfile

#@Author:::Sandeep Kumar Sharma

#outlook application refrence
outlook_app=0
#outlook ids to access different folders look into msdn for more info.
not a preffered way as i am hardcoding data here
OlDefaultFolders={'olFolderCalendar':9,'olFolderConflicts':
19,'olFolderContacts':10,'olFolderDeletedItems':3,'olFolderDrafts':
16,'olFolderInbox':6,'olFolderJournal':11,'olFolderJunk':
23,'olFolderLocalFailures':21,'olFolderNotes':12,'olFolderOutbox':
4,'olFolderSentMail':5,'olFolderServerFailures':
22,'olFolderSyncIssues':20,'olFolderTasks':
13,'olPublicFoldersAllPublicFolders':18}
#outlook types to save mailItem look into msdn for more info
#although doesnot work for me :-(
OlSaveAsType={'olTXT': 0,'olRTF':1,'olTemplate': 2,'olMSG': 3,'olDoc':
4,'olHTML':5,'olVCard': 6,'olVCal':7,'olICal': 8};

#refrence to content in inbox
inbox_obj=0

#function which will initialise outlook and return its reference
def getAppRef():
temp=win32com.client.Dispatch("OutLook.Application")
return temp.GetNamespace("MAPI")

#function to return the folders in the outlook
def getOutLookFolders(a,b=OlDefaultFolders['olFolderInbox']):
return a.GetDefaultFolder(b)

#function to get email content
def getMailContent(obj):
txt_file=codecs.open('data.html',encoding='utf-8',mode='w')
emailData=""
for kk in range(len(obj.Items)-1,0,-1):
print 'writting file='+str(kk)
mailItem=obj.Items[kk]
emailData=emailData+getEmailData(mailItem)
saveAttachments(mailItem.Attachments)
txt_file.write(getHTMLString(emailData))
txt_file.close()

#function which will return the emailItem data as form of String
def getEmailData(mailItem):
data="<p>"
sender='<h4>SenderName</
h4>'+checkStringType(mailItem.SenderName)
time='<br><h4>Time</
h4>'+checkStringType(str(mailItem.ReceivedTime))
attachment='<br><h5>Attachments Count</
h5>'+str(len(mailItem.Attachments))
edata='<h4>Email Content</h4>'+checkStringType(mailItem.Body)+"</
p><hr/>"
dataToWrite=data+sender+time+attachment+edata
return dataToWrite

#function for saving the attachment.we are calling attachments
SaveAsFile to save the attachment.
#SaveAsFile is com method.for more info dig into msdn :)
def saveAttachments(atmts):
for kk in range(1,len(atmts)):
atmt=atmts[kk]
abc=os.path.isdir(os.getcwd()+'\email')
if(abc==True):
print 'directory exists'
else:
os.mkdir(os.getcwd()+'\email')
path=os.path.abspath(os.getcwd()+'\email')
atmt.SaveAsFile(path+"\\"+atmt.DisplayName)

# function to check whether the character encoding is ascii or smthing
else
def checkStringType(a):
if isinstance(a,str):
b='not a unicode string'
else:
a.encode('utf-8')
#print 'unicode type'
return a

#bit of html stuff so that i can see my output on browsers.
def getHTMLString(emailData):
a='<html><head><title>Your Email Data log is here</title></
head><body>'+emailData+'</body></html>'
return a

#main entrance to the program
def main():
global outlook_app,inbox_obj
outlook_app=getAppRef()
inbox_obj=getOutLookFolders(outlook_app)
getMailContent(inbox_obj)

main()

once again thanks for your help.

thanks and regards
sandeep kumar sharma
 
G

Gabriel Genellina

thanks for ur replies. i have a bit closer look at my code and i am
able to fix the problem.now my exe is working fine.the code is bit
more cleaner now as i removed lot of unused function from it and try
to document it also.

Glad to see it worked finally. Just a few comments:
#function which will initialise outlook and return its reference
def getAppRef():
temp=win32com.client.Dispatch("OutLook.Application")
return temp.GetNamespace("MAPI")

Instead of a comment, use a docstring
<http://docs.python.org/tut/node6.html#SECTION006600000000000000000>

def getAppRef():
"""Initialise outlook and return its reference."""
...
abc=os.path.isdir(os.getcwd()+'\email')
if(abc==True):
print 'directory exists'
else:
os.mkdir(os.getcwd()+'\email')
path=os.path.abspath(os.getcwd()+'\email')
atmt.SaveAsFile(path+"\\"+atmt.DisplayName)

Use '\\email' instead, or r'\email'. \ is the escape character, '\temp'
actually isn't what you may think. The rules:
<http://docs.python.org/ref/strings.html>
Anyway, it's much better to use os.path.join to build a path:

email_dir = os.path.abspath(os.path.join(os.getcwd(), 'email'))
abc = os.path.isdir(email_dir)
if abc:
print 'directory exists'
else:
os.mkdir(email_dir)
atmt.SaveAsFile(os.path.join(email_dir, atmt.DisplayName))
# function to check whether the character encoding is ascii or smthing
else
def checkStringType(a):
if isinstance(a,str):
b='not a unicode string'
else:
a.encode('utf-8')
#print 'unicode type'
return a

This function does not perform what the comment says.
The b='...' is useless, and the a.encode(...) line *returns* a string
(which is immediately discarded) - it does not modify `a`, strings in
Python are immutable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top