[python-win32] Re: Closing COM object (e.g. Excel) when Python app dies

Roger Upole rwupole at msn.com
Mon Mar 6 07:51:41 CET 2006


Warren Sande wrote:

> have a PythonCard app that opens up an Excel spreadsheet using the
> win32com module. 
> 
> I started doing this in Perl, then recently switched to Python (and
> PythonCard), which I am just learning.
> 
> In Perl, I found the following code snippet which I used in my app:
> 
> ----------------------
> # use existing instance if Excel is already running
>  eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
>  die "Excel not installed" if $@;
>  unless (defined $ex) {
>      $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
>              or die "Oops, cannot start Excel";
>      $ex->{Visible} = 1;
> }  # Note the destructor specified on the Win32::OLE->new method. 
>     # It ensures that Excel will shutdown properly even if the Perl
> program dies.
> ----------------------
> 
> I would like to be able to do the same in Python, but don't know if it
> is supported, and can't find or figure out the syntax if it is.
>  
> I know this is not really a PythonCard question, but I'm hoping that
> other PythonCard users are working with win32com and might be able to
> help me out.
> 
> My code to open the excel object is simply this:
>  
> ----------------------
> import win32com as wc
> ...
>  
> self.xl = wc.Dispatch("Excel.Application")
> self.xl.Visible = 1
> ...
>  
> self.xl.Quit()
> ----------------------
 
You can add a __del__ method to your class:

import win32com.client
class xlautodestruct:
    def __init__(self):
        self.xl=win32com.client.Dispatch('Excel.Application')
        self.xl.Visible=1
    def __del__(self):
        self.xl.Quit()

    hth
        Roger




More information about the Python-win32 mailing list