views:

522

answers:

2

Here is an example of the problem I am running into. I am using the Python Win32 extensions to access an Outlook mailbox and retrieve messages.

Below is a script that should write "hello world" to a text file. I need to grab some messages from an Outlook mailbox and I noticed something weird. After I attach to the mailbox once, I can no longer print anything to a file. Here is a trimmed down version showing the problem:

#!/usr/bin/env python

from win32com.client import Dispatch

fh = open('foo.txt', 'w')
fh.write('hello ')
fh.close()

session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\nprodreport');
session.Logoff()

fh = open('foo.txt', 'a')
fh.write('world')
fh.close()

If I don't attach to the mailbox and comment out the following lines, it obviously works fine:

session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\ncorey');
session.Logoff()

Why is opening a session to a mailbox in the middle of my script blocking further file output? any ideas? (other operations are not blocked, just this file i/o asfaik)

A: 

answering my own question. it looks like your working directory gets changed when you read the email. If you set it back, your file i/o works fine.

the correct script would look like this:

#!/usr/bin/env python

import os
from win32com.client import Dispatch

fh = open('foo.txt', 'w')
fh.write('hello ')
fh.close()

cwd = os.getcwd()

session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\ncorey');
session.Logoff()

os.chdir(cwd)

fh = open('foo.txt', 'a')
fh.write('world')
fh.close()
Corey Goldberg
+1  A: 

Yes, the directory change is a known gotcha when using CDO/MAPI. It is "documented" somewhere in MSDN (eg http://support.microsoft.com/kb/269170). You can reproduce it easily in Python like this:


import os
import win32com.client

print os.getcwd ()
win32com.client.Dispatch ("MAPI.Session")
print os.getcwd ()

TJG