Friday, December 16, 2016

Connecting Python to the SAP GUI

So I know you can script SAP GUI actions using Visual Basic. SAP even has a built in recorder but I don't use VB I use Python. I'm not going to debate the better language here that has been done. What I am going to do is provide some how to's on scripting SAP GUI with Python.

Python 2.7 to be exact but the same should work in Python 3.5. If you don't have Python installed you can get it here. Also I'll be using PyCharm Community edition but you can use any IDE you prefer. You can even use something like Notepad++ or plan old Notepad but I don't recommend Notepad as it has no syntax highlighting which will make it much easier.

Also I assume you have a working knowledge of SAP GUI usage and Python. If you don't know SAP you shouldn't be doing this. If you need some work on Python you can check out YouTube for many tutorials along with multiple websites.

For SAP I'll be using 740.

SAPVersionInfo.png




















If you are on a different SAP version your controls used may be different.

So first things first as they say. To do anything with gui scripting you first have to connect to the SAP GUI scripting com object. In Python that is done using the win32com.client module.

 import win32com.client  

So now we can connect to an already open SAP GUI session. It only takes 2 lines of code. Real simple right?

 SapGui = win32com.client.GetObject("SAPGUI").GetScriptingEngine  
 session = SapGui.FindById("ses[0]")  

That's it. Given it won't do anything but it connects and then disconnects from your first open SAP session. You will know this by the spinning barber pole on the right of the SAP status bar.




11 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi Jason,
    Great blog so far and it's the best I could find on this topic.

    I've been extremely frustrated using VBA with SAP scripts, so this blog was a great start for me to develop a more stable approach for extracting data from SAP using python.

    I'd like to share an app I've developed that I think every Business Analyst needs to work with the SAP GUI.

    Here are some of the features:
    - Launch & Close the SAP GUI
    - Multithread multiple SAP sessions at once
    - Handle a queue of SAP routines
    - Optimize of the order of the parallel SAP routines to minimize runtime
    - Specify user-defined timeouts to kill the thread pool if SAP hangs up

    Please contact me at shanelanan@yahoo.com. I would like to add my python module with an example to your blog, but posting in this text field will look ugly.

    ReplyDelete
    Replies
    1. Hello Shane,

      Do you mind sharing with us what approach should be taken in Python to accomplish some of the items that you mentioned in your response?

      In particular:

      -How to process multiple SAP sessions from within Python at the same time;

      -How to handle the queue of requests to SAP?

      I am a Python newbie, although with quite a bit of SAP GUI automation experience using VBA.

      Thank you,

      Max

      Delete
  3. Hi,

    I made a script to open SAP with python.

    from win32com.client import Dispatch
    #reference sapfewse.ocx like a dll file with makepy()
    app = win32com.client.Dispatch("Sapgui.ScriptingCtrl.1")
    conn = app.OpenConnection("System_Name", True)
    ses = conn.Children

    I am able to open the SAP GUI Scripting window with the code but, I think there is a problem with the Children(0) part as it does not allow me to use the ses.FindByID to access the ID tags. If I use your original python script with a manually opened SAP session, there is no problem accessing the FindByID. Any tips?





    ReplyDelete
  4. Maseyh,

    Your issue is that not enough time has elapsed when trying to get the child object. Python is executing too fast for the SAP COM library to catch up!

    from subprocess import call
    import win32com.client
    import time

    GUIPath = 'C:/Program Files (x86)/SAP/FrontEnd/SAPgui/'
    WinTitle = 'SAP'
    SID = 'xxxxxx.sap.xxxxx.com'
    InstanceNo = 'xx'

    shell = win32com.client.Dispatch("WScript.Shell")
    cmdString = os.path.join(GUIPath, 'SAPgui.exe') + " " + SID + " " + InstanceNo

    call(cmdString)
    while not shell.AppActivate(WinTitle):
    time.sleep(1)


    checkGUIandSess0 = False
    while not checkGUIandSess0:
    try:
    SAP = win32com.client.GetObject("SAPGUI").GetScriptingEngine
    S0 = SAP.FindById("ses[0]") # session
    checkGUIandSess0 = True
    except:
    time.sleep(1)
    continue

    S0.FindById("wnd[0]").maximize()

    """
    Things to do here:
    - enter username and password
    - handle company specific popups and messages
    """


    ReplyDelete
  5. Hi Jason, thanks for sharing. Do you know why

    import win32com.client

    SapGui = win32com.client.GetObject("SAPGUI").GetScriptingEngine
    session = SapGui.FindById("ses[0]")

    session.StartTransaction(Transaction="IE03")

    Returns

    Traceback (most recent call last):
    File "Sap.py", line 4, in
    session = SapGui.FindById("ses[0]")
    File ">", line 3, in FindByIdpywintypes.com_error: (-2147352567, 'Exception occurred.', (619, 'saplgpad', 'The control could not be found by id.', 'C:\\Program Files (x86)\\SAP\\FrontEnd\\SAPgui\\saplgpad.HLP', 393215, 0), None)

    Would very much appreciate your answer.
    Thanks.

    Marcus


    ReplyDelete
  6. how to create a two session in sap by using Python script

    ReplyDelete
  7. import win32com.client
    import sys
    import subprocess
    import time
    path = r"C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe"
    subprocess.Popen(path)
    time.sleep(10)
    SapGuiAuto = win32com.client.GetObject('SAPGUI')
    application = SapGuiAuto.GetScriptingEngine
    connection = application.OpenConnection("01) [SSO]", True)
    session = connection.Children(0)
    session.findById("wnd[0]/usr/txtRSYST-BNAME").text = "username"
    session.findById("wnd[0]/usr/pwdRSYST-BCODE").text = "password@4"
    session.findById("wnd[0]").sendVKey(0)


    above code will help to create seesion for sap. But need to create one more seeion. Please help on the same. It very helpful for me. Thanking you in advance.

    Contact details: 7382088004
    mail id: pavankmr080@gmail.com

    ReplyDelete
  8. when I run my code and connect to an already open SAP GUI session, it's ok.
    But when I create one file with cmd "pyinstaller" and run this file, this exe file can not access my already open SAP GUI session. Can you help me, please? thanks so much!!!
    and this is my code :
    SapGui = win32com.client.GetObject("SAPGUI").GetScriptingEngine
    session = SapGui.findByid("Ses[0]")

    ReplyDelete
    Replies
    1. Hi man, try with: pyinstaller xxx.py --windowed

      Delete