def ensure_excel_is_not_running(): import pythoncom import pywintypes try: if pythoncom.GetActiveObject("Excel.Application") != None: raise Exception("Close all instances of Excel before starting the tests.") except pywintypes.com_error: pass # Desired case
def wait_for_excel_exit(): """Wait for Excel to exit by polling the running object table. This may be useful following Application.Quit Excel will not exit until all COM clients are released. This function encourages garbage collections, to release stale refs held by pythoncom""" import pythoncom import pywintypes import time import gc global _time_waiting_for_excel_exit wait_start = datetime.datetime.now() for i in xrange(5): try: # We are interested only in failure, not the return value # The return value - if captured in the future - must not # live beyond the gc.collect() call below pythoncom.GetActiveObject("Excel.Application") # Excel is running gc.collect( ) # Release interface pointers with no python refs before trying again time.sleep(1) except pywintypes.com_error: return raise Exception("Excel failed to terminate")
def GetActiveObject(Class, clsctx = pythoncom.CLSCTX_ALL): """ Python friendly version of GetObject's ProgID/CLSID functionality. """ resultCLSID = pywintypes.IID(Class) dispatch = pythoncom.GetActiveObject(resultCLSID) dispatch = dispatch.QueryInterface(pythoncom.IID_IDispatch) return __WrapDispatch(dispatch, Class, resultCLSID = resultCLSID, clsctx = clsctx)