SAP GUI Scripting Script Generator for Python
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.
Fill in
Exactly as shown in SAP Logon.
sap_gui_script.py
# Requires: SAP GUI for Windows with scripting enabled, Python on Windows, pip install pywin32
import getpass
import win32com.client
import pywintypes
ATTACH = 'Yes' == '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('PRD - Production', True)
session = connection.Children(0)
session.findById('wnd[0]/usr/txtRSYST-MANDT').text = '100'
session.findById('wnd[0]/usr/txtRSYST-BNAME').text = 'JSMITH'
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 = '/nMM03'
session.findById('wnd[0]').sendVKey(0)
session.findById('wnd[0]/usr/ctxtRMMG1-MATNR').text = 'MAT-10045'
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'C:\temp\out.txt', '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
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
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.
Have a script reviewed before it touches production
Send us the recorded steps and target transaction and we will point out where it will break and whether a BAPI is a better route.
Optional. The tool and every export work without this. No spam.
How to use it
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.
- 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
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
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
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.
Frequently Asked Questions
How do I enable SAP GUI Scripting?
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?
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?
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?
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.
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.
Related Tools
SAP Kernel Upgrade Command Generator (Linux, SAPCAR)
Fill in SID, instance numbers, paths and archive names and get the ordered shell commands for a kernel patch on an ABAP system or SAP Web Dispatcher on Linux.
Developer ToolsABAP Selection Screen and SELECT-OPTIONS Generator
Builds a complete ABAP report with a framed selection screen, two SELECT-OPTIONS, a parameter, radio buttons that hide a field, event blocks, validation, an optional option restriction and an ALV output.
Developer ToolsABAP CDS Table Function with AMDP Generator
Builds the three parts of a CDS table function: the DDL definition with client handling and parameters, the AMDP class with SQLScript, and the ABAP SQL call that consumes it.
More Developer Tools tools
See all- ABAP New Open SQL Syntax Reference by Release (7.40 to 7.58)
- ABAP ALV Layout, Field Catalog and Color Codes Reference
- SAP Gateway SEGW DPC_EXT CRUD Methods Generator (ABAP)
- SAP Sales Order ABAP SELECT Generator (VBAK, VBAP, VBFA)
- SAP Sales Order Create BAPI ABAP Generator (BAPI_SALESORDER_CREATEFROMDAT2)
- SAP ABAP Open Items SELECT Generator
- SAP ACDOCA SQL Query Generator
- SAP QM Inspection Lot ABAP SELECT Generator
- SAP Quality Notification Pareto SQL Query Generator
Keep exploring
Free tools
- SAP GUI Connection Error Codes Reference (88, 10054, 10061)Reference for SAP GUI connection errors by layer: Windows socket codes, SAP NI layer codes, message server and logon group errors and SNC errors, with checks and fixes.
- SAP NetWeaver Release to SAP_BASIS and Kernel ReferenceWhich SAP_BASIS release belongs to each NetWeaver and ABAP Platform release, which products run on it, which kernel lines apply and how to check your own system.
- ABAP ALV Layout, Field Catalog and Color Codes ReferenceSide by side: how to do checkbox, hotspot, colors, subtotals, toolbar buttons, top of page and refresh in CL_GUI_ALV_GRID and in CL_SALV_TABLE, plus the C1 to C7 color codes.
ERP fixes and how-tos
- SAP App for Mac and PC: Install SAP GUI or Use the BrowserHow to run SAP on a Mac or PC: SAP GUI for Java, SAP GUI for Windows, SAP Business Client or browser Fiori, with common install errors and fixes.
- Calling SAP APIs from Python: OData with requests, Authentication and PyRFCCall SAP from Python with the requests library: authentication, filtering, paging and CSRF tokens for OData, plus when PyRFC and RFC make sense.
- Infor ION Scripting and ETL: Transformation Options ExplainedInfor ION scripting and ETL explained: mapping and transformation in document flows, where scripting fits, and when to use Data Lake flows or another ETL tool.