9

I have a script where I use win32com to interact with a COM service. It works as intended when the program is already open. I connect to it using win32com.client.dynamic.Dispatch, then interact with a document that should already be open. Assuming the program is already open, I can easily check if a document is open, but I'm not sure how to check if the program is already open or not. When I use the Dispatch mentioned, it just starts the program if it isn't already open, which is not what I want.

Scott B
  • 2,542
  • 7
  • 30
  • 44

1 Answers1

21

try win32com.client.GetActiveObject() method. This is what I use in some convenience functions I've written, this one for Excel:

def Excel(visible=True):
    '''Get running Excel instance if possible, else 
    return new instance. 
    '''
    try: 
        excel = win32com.client.GetActiveObject("Excel.Application")
        print("Running Excel instance found, returning object")

    except:
        excel = new_Excel(visible=visible)
        print("No running Excel instances, returning new instance")

    else:
        if not excel.Workbooks.Count:
            excel.Workbooks.Add(1)
        excel.Visible = visible

    return excel

new_Excel is just another convenience function for opening new instances of the Excel application object.

nitetrain8
  • 254
  • 3
  • 6
  • 2
    How would you handle the case when Excel isn't installed? If I use `excel = win32.Dispatch('excel.application')`, it crashes if Excel isn't installed: `pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)` How do I gracefully check first before trying to send the Dispatch? – Frak Dec 04 '18 at 00:46
  • https://stackoverflow.com/questions/73096832/use-python-to-detect-excel-installation – crazydan Aug 19 '23 at 03:31