# SAP GUI Scripting Script Generator for Python

> Source: https://netray.co/tools/sap-gui-scripting-python-script-generator
> Publisher: Netray (netray.co), AI and integration engineering for ERP and manufacturing systems.
> Section: Free Tools

## Short answer

Builds a runnable Python script that drives SAP GUI for Windows through the SAP GUI Scripting API: connect, log on to a client, call a transaction, set a field and capture the result.

## Category

developer

## Erp

SAP NetWeaver / Basis

## Audience

- SAP developer
- SAP power user
- Automation engineer

## Tool

**Kind:** template

**Output:** code

**Language:** python

**Fields:**

#### SAP Logon connection description

**Key:** conn

**Type:** text

**Default:** PRD - Production

**Help:** Exactly as shown in SAP Logon.

#### Client

**Key:** client

**Type:** text

**Default:** 100

#### SAP user (used only when opening a new connection)

**Key:** user

**Type:** text

**Default:** JSMITH

#### Attach to an already open session

**Key:** attach

**Type:** select

**Options:**

- Yes
- No

**Default:** Yes

#### Transaction code

**Key:** tcode

**Type:** text

**Default:** MM03

#### First field ID

**Key:** fieldid

**Type:** text

**Default:** wnd[0]/usr/ctxtRMMG1-MATNR

#### Value to enter

**Key:** value

**Type:** text

**Default:** MAT-10045

#### Result file path

**Key:** export

**Type:** text

**Default:** C:\temp\out.txt

**Blocks:**

#### sap_gui_script.py

**Body:** # Requires: SAP GUI for Windows with scripting enabled, Python on Windows, pip install pywin32
import getpass
import win32com.client
import pywintypes

ATTACH = '{{attach}}' == 'Yes'

def get_session():
    sap_gui = win32com.client.GetObject('SAPGUI')
    application = sap_gui.GetScriptingEngine
    if ATTACH:
        connection = application.Children(0)
        return connection, connection.Children(0), False
    connection = application.OpenConnection('{{conn}}', True)
    session = connection.Children(0)
    session.findById('wnd[0]/usr/txtRSYST-MANDT').text = '{{client}}'
    session.findById('wnd[0]/usr/txtRSYST-BNAME').text = '{{user}}'
    session.findById('wnd[0]/usr/pwdRSYST-BCODE').text = getpass.getpass('SAP password: ')
    session.findById('wnd[0]').sendVKey(0)
    return connection, session, True

def main():
    connection = None
    opened = False
    try:
        connection, session, opened = get_session()
        session.findById('wnd[0]/tbar[0]/okcd').text = '/n{{tcode}}'
        session.findById('wnd[0]').sendVKey(0)
        session.findById('{{fieldid}}').text = '{{value}}'
        session.findById('wnd[0]').sendVKey(0)
        # Close a popup (for example the MM03 view selection) with Enter
        if session.ActiveWindow.Name == 'wnd[1]':
            session.findById('wnd[1]').sendVKey(0)
        status = session.findById('wnd[0]/sbar')
        title = session.findById('wnd[0]').Text
        result = 'Title: %s | Status type: %s | Status: %s' % (title, status.MessageType, status.Text)
        print(result)
        with open(r'{{export}}', 'w', encoding='utf-8') as f:
            f.write(result + '\n')
    except pywintypes.com_error as err:
        print('SAP GUI Scripting error:', err)
    finally:
        if opened and connection is not None:
            connection.CloseConnection()

if __name__ == '__main__':
    main()

#### Server and client prerequisites

**Body:** RZ11 (or profile): sapgui/user_scripting = TRUE
Optional: sapgui/user_scripting_per_user = TRUE, then grant authorization object S_SCR only to scripting users
SAP GUI Options > Accessibility & Scripting > Scripting: Enable scripting
Capture field IDs with Customize Local Layout (Alt+F12) > Script Recording and Playback

**Notes:** Verify field IDs on your release by recording the same steps once: IDs change with the screen, screen variant, GUI theme and SAP GUI release. A profile parameter changed in RZ11 is not permanent until it is in the instance profile. Do not hardcode passwords; this script prompts with getpass or reuses an open session. Status bar MessageType values are S, W, E, A and I.

## Content

**Intro:** This generator writes a Python script that drives SAP GUI for Windows through the SAP GUI Scripting API using pywin32. It attaches to an open session or opens a named SAP Logon connection, runs a transaction, fills a field and records the status bar.

**Sections:**

#### How to use it

**Body:** Enter the SAP Logon description exactly as it appears in SAP Logon, the client, the transaction and the first field ID with the value to enter. Choose Yes for attach when a user is already logged on: the script uses the first connection and first session, which avoids handling passwords at all. Choose No to open a new connection; the script fills client and user and asks for the password at run time. Install pywin32, save the file and run it with python sap_gui_script.py while SAP GUI is open. Record the remaining steps of your transaction and paste the recorded findById lines after the first field.

**Bullets:**

- One findById line per recorded step; keep IDs from your own recording.
- sendVKey(0) is Enter, sendVKey(3) is Back (F3), sendVKey(8) is Execute (F8).
- Read wnd[0]/sbar after each save to catch errors.

#### How the SAP GUI Scripting object model works

**Body:** GetObject('SAPGUI') returns the SAP GUI ROT entry, and GetScriptingEngine gives the GuiApplication. Under it, Children holds GuiConnection objects (one per SAP Logon connection) and each connection's Children holds GuiSession objects (one per window). findById walks the component tree with IDs such as wnd[0]/usr/ctxtRMMG1-MATNR, where wnd[0] is the main window, usr the user area, ctxt the control type (a text field with value help) and RMMG1-MATNR the screen field. The status bar is wnd[0]/sbar; its Text and MessageType tell you whether the step worked.

#### Enabling scripting on server and client

**Body:** Scripting is off by default. On the server, a Basis admin sets profile parameter sapgui/user_scripting to TRUE (RZ11 for a test, the instance profile to make it permanent). Setting sapgui/user_scripting_per_user to TRUE adds a second gate: only users holding authorization object S_SCR may script, which is the controlled option for production. On the PC, enable scripting under SAP GUI Options, Accessibility and Scripting, and decide whether users see a notification when a script attaches. Related parameters such as sapgui/user_scripting_set_readonly limit scripts to reading data.

#### Best practices and when not to script

**Body:** GUI scripting replays screens, so it breaks when a screen, variant or popup changes. Use it for one-off data checks, mass display jobs and testing, not for high-volume postings. For postings, BAPIs, IDocs or LSMW are safer because they validate and log. Add a check of the status bar MessageType after every save, stop on E or A, and write a log line per record. Run scripts under a named user with S_SCR, never a shared dialog user, and keep the script in version control with the SAP release it was recorded on.

**Cta:** If you want users to ask SAP for material, order or stock details in plain English instead of scripting screens, we can run that on your own servers with read-only access.

**Faq:**

#### How do I enable SAP GUI Scripting?

**Answer:** Two switches. The server parameter sapgui/user_scripting must be TRUE (set in RZ11 and the instance profile), and on the PC scripting must be enabled under SAP GUI Options, Accessibility and Scripting. If sapgui/user_scripting_per_user is TRUE, the user also needs authorization object S_SCR.

#### Can I use SAP GUI Scripting from Excel?

**Answer:** Yes. The same API is available from VBA: GetObject("SAPGUI").GetScriptingEngine, then Children(0) for connection and session and findById for fields. The Python script here follows the same object model, so recorded lines translate one to one. Excel VBA is common for loading rows from a sheet into a transaction.

#### Where do I find the field IDs for findById?

**Answer:** Record the steps with Script Recording and Playback from the Customize Local Layout menu (Alt+F12). The generated VBS file contains every findById call. Tools such as the SAP GUI Scripting Tracker also show the component tree. Always record on the same release and screen variant your users run.

#### Why does my script fail with a COM error on findById?

**Answer:** The ID does not exist on the current screen. Common causes are an unexpected popup, a different screen variant or tab, a GUI release with different IDs, or running before the previous step finished. Check session.ActiveWindow.Name and the status bar before the failing line, and re-record the step.

## Search terms

sap gui scripting, sap gui scripting examples, sap gui scripting api, sap gui scripting api excel, sap gui scripting best practices, sap gui scripting python, win32com sap gui

---
Talk to an engineer: https://netray.co/contact?intent=erp_ai | Machine catalog: https://netray.co/agent/catalog.json
