Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COM: excelApplication.Application.Quit() preserves the process

I'm using COM integration to drive MS Excel from Python 2.7. I noticed a peculiar thing: when I run the following bit of code:

import win32com.client
excelApp = win32com.client.dynamic.Dispatch('Excel.Application')

an EXCEL.EXE process appears on the processes list (which view using the Windows Task Manager or subprocess.Popen('tasklist')) as expected. I then do all the stuff I need to do no problem. However, when I close Excel:

excelApp.Application.Quit()

The process persists, even if I close the Python interpreter which started it (this kind of makes sense as Excel runs in a different process but just to be sure). The only way I've found to terminate this process is either by hand, using the Task Manager, or by calling:

subprocess.Popen("taskkill /F /im EXCEL.EXE",shell=True)

the forceful /F flag is necessary, otherwise the process doesn't terminate.

This isn't really a problem (I hope) but I wanted to ask whether this could cause issues when I first edit the documents "normally", then when calling Excel from python and then "normally" again? Potentially many (couple dozens) times in a row? What I'm worried about is creating conflicting versions of documents etc. Or should I just terminate the EXCEL.EXE process each time just to be safe?

Also I noticed that subprocess.Popen("taskkill") doesn't return any exceptions that I can catch and anylse (or am I doing something worng here?). I'm particularly interested in distinguishing between the "non-existent process" kill attempt and a failed attempt to terminate the process.

like image 836
Aleksander Lidtke Avatar asked Aug 24 '13 17:08

Aleksander Lidtke


1 Answers

try closing any open books, telling the app to quit and delete any references to the app. I usually wrap my com objects in a class. This is what my quit method looks like.

      def quit(self):
        self.xlBook.Close(SaveChanges=0)
        self.xlApp.Quit()
        del self.xlApp

Are you calling Dispatch from the main thread? If not be sure to call

pythoncom.CoInitialize()

before Dispatch, and

pythoncom.CoUninitialize()

after Quit

like image 101
user2682863 Avatar answered Oct 19 '22 03:10

user2682863