win32comsap-guipythoncommoniker

Error with win32com.client.GetObject when connecting to SAP GUI


Dears, first of all this is the first time I ask a question on Stackoverflow so forgive me if I'm not following the right way to do this.

I kindly ask for your help as I'm facing an issue with win32com. I'm trying to connect to SAP GUI in order to automate certain tasks.

import win32com.client

SapGuiAuto = win32com.client.GetObject('SAPGUI')

I get the following error (until yesterday everything was working fine..):

Traceback (most recent call last):
  File "C:/Users/xxxxx/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/PySAPscript.py", line 157, in <module>
    SAP_OP()
  File "C:/Users/xxxxx/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/PySAPscript.py", line 18, in SAP_OP
    SapGuiAuto = win32com.client.GetObject('SAPGUI')
  File "C:\Users\xxxxx\PycharmProjects\yyyyyy\venv\lib\site-packages\win32com\client\__init__.py", line 72, in GetObject
    return Moniker(Pathname, clsctx)    
  File "C:\Users\xxxxxx\PycharmProjects\yyyyyyy\venv\lib\site-packages\win32com\client\__init__.py", line 87, in Moniker
    moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
pywintypes.com_error: (-2147221020, 'Invalid syntax.', None, None)

I've found some documentation about this issue which suggests using pythoncom.CoInitialize():

Using win32com with multithreading

However I can't figure out how to use this function for my purpose.

Thank you for your help!


Solution

  • I had the same issue when trying to run SAP GUI Script triggered from Flask (desktop) application. Solution that works for me is to embrace the code operating with SAP GUI with pythoncom.CoInitialize() and pythoncom.CoUinitialize() statements:

    import win32com.client
    import pythoncom
    
    def display_document():
        pythoncom.CoInitialize()
    
        sap_gui = win32com.client.GetObject("SAPGUI")
        sap_app = sap_gui.GetScriptingEngine
        sap_conn = sap_app.Children(0)
        sap_session = sap_conn.Children(0)
        sap_session.StartTransaction("FB03")
    
        pythoncom.CoUninitialize()