COM client and exceptions

Blair Hall b.hall at irl.cri.nz
Mon Jul 8 17:50:52 EDT 2002


I am not sure how to handle Python exceptions when Python 
is using Excel as a client.

At present, if Python raises
an exception while it has an active reference to Excel, then the
behaviour of Excel  is damaged until I close Pythonwin
and start all over again (worse it is sometimes necessary to reboot).

For example, using the class defined below, I can write

>>> xl = Excel('test')

and then to provoke the problem type 

>>> xl.problem()

After which Excel does not operate properly. So for example, typing

>>> xl = Excel("test2")

does not open Excel properly: only part of the Excel toolbar on screen.

I  am using win95 with the latest version of Python and the windows
extensions.

What should I be doing to keep Excel happy? 
Indeed, where should I be looking (documentation?)
to find out how to write more stable Com-Python code?


#########################################
import win32com.client
import pythoncom

def comExceptionHandler(hr,msg,exc,arg) :
    print 'COM call failed: %s' % msg
    if exc is not None:
        wcode, source, text, helpFile, helpID, scode = exc
        print 'Error source:',source
        print text
        print 'See also: %s (id=%d)' % (helpFile,helpID)

class Excel:
    def __init__(self,filename,visible=1):
        """
        Create a new file in the current working directory
        and save a new Excel workbook in it.
        """
        import os
        filename = os.path.join( os.getcwd(), filename )
        try:
            self.app = win32com.client.Dispatch("Excel.Application")
            wb = self.app.Workbooks.Add()
            wb.SaveAs(filename)
            wb.Activate()
            self.app.Visible = visible
        except pythoncom.com_error, (hr,msg,exc,arg):
            comExceptionHandler(hr,msg,exc,arg)

    def __del__(self):
        wb = self.app.ActiveWorkbook
        wb.Save()
        self.app.Quit()

    def problem(self):
        raise "something" # Just raise an exception to show problem






More information about the Python-list mailing list