SAP GUI & RFC Automation
A comprehensive Python module for automating SAP GUI operations (SAP Scripting) and RFC (Remote Function Call) integration. Designed to easily integrate with modern RPA frameworks (e.g., Robocorp) and standard Python automation scripts.
Business Benefits
- Increased Efficiency: Automate repetitive manual data entry, extraction tasks, and transactions in SAP without human intervention.
- Reduced Errors: Eliminate human error in routine transactions by relying on precise GUI element interaction and structured RFC calls.
- Scalability: Seamlessly integrate SAP processes into larger, multi-system RPA orchestrations.
- Data Export & Transformation: Effortlessly extract SAP GridView and TableControl data directly into modern formats like Pandas DataFrames, CSV, and Excel for immediate downstream analytics.
Architecture & Structure
The project is modularized into core interaction capabilities and higher-level automation utilities:
-
rpa_sap/core/: Contains the foundational layers for SAP interaction.connection.py: Manages SAP Logon connections, active process handling, and explicit logins.session.py: Handles individual SAP sessions and RFC execution wrappers.ui_automation.py: Provides direct interaction capabilities with standard SAP GUI elements (buttons, fields, trees, dialogs).
-
rpa_sap/lib/: Advanced handlers for complex SAP controls and specific workflows.GridView.py: Utilities for reading, scrolling, and extracting data from SAP GridView components.GuiTableControl.py: Utilities for managing standard SAP Table Controls.SQ01.py: Automation features for SAP query execution workflows (SQ01).
Installation
To install the package, run:
pip install rpa-sap
Requirements & Dependencies
- Python >= 3.10
- SAP GUI Scripting must be enabled on the server and client.
- Dependencies:
pandas,pywin32,wmi,python-dotenv,openpyxl
How to Use (Examples)
1. Opening a New SAPGUI Session
The connection_string should be the exact name of the connection as defined in your SAP Logon application (e.g., "S4HANA Prod"), or a direct SAP connection string (e.g., "/H/192.168.1.1/S/3200").
from rpa_sap import ConnectionManager
manager = ConnectionManager()
session = manager.open_new_session(
connection_string="My SAP System", # Exact name from SAP Logon
user_id="user_id",
password="password",
client="100",
language="EN"
)
Alternatively, you can attach to an already running SAP session without logging in again:
# Attach to an existing session by system details
session = manager.activate_session(
user_id="user_id",
sid="PRD",
application_server="192.168.1.1",
client="100"
)
When you are finished, you can explicitly clean up sessions:
manager.close_session(session)
manager.close_all_sessions()
manager.close_sap_logon()
2. Interacting with UI Elements
The session.interactor exposes an ElementInteractor which provides high-level, robust methods to manipulate SAP GUI objects easily.
# Assuming you have an active session
# Set a transaction code (e.g., MM03) in the command field
session.interactor.set_text("wnd[0]/tbar[0]/okcd", "MM03")
# Press the Enter key
session.interactor.press_enter()
# Press a specific button by its ID
session.interactor.press_button("wnd[0]/tbar[1]/btn[8]")
# Check or uncheck a checkbox
session.interactor.set_checkbox_state("wnd[0]/usr/chk[1,1]", True)
# FindElemendById is also available via session object.
session.findById("wnd[0]/tbar[0]/okcd").text = "MM03"
session.findById("wnd[0]").sendVKey(0)
# Wait for an element to load before proceeding (crucial for RPA synchronization)
session.interactor.wait_until_object_exists("wnd[0]/usr/ctxtRM06E-EBELN", timeout=30)
# You can also use the transaction context manager to ensure safe cleanup
with session.transaction("ME32L"):
session.interactor.set_text("wnd[0]/usr/ctxtRM06E-EBELN", "4500000001")
session.interactor.press_enter()
3. Extracting Data from GridView
from rpa_sap.lib.GridView import GridView
from rpa_sap.lib.data_extractors import GridViewExtractor
# Initialize the GridView helper with the active session
grid = GridView(session)
extractor = GridViewExtractor(grid)
# Extract data directly to a Pandas DataFrame
df = extractor.to_dataframe("wnd[0]/usr/cntlGRID1/shellcont/shell")
print(df.head())
# Alternatively, extract data directly to a file
extractor.to_csv("wnd[0]/usr/cntlGRID1/shellcont/shell", "output.csv")
extractor.to_xlsx("wnd[0]/usr/cntlGRID1/shellcont/shell", "output.xlsx")
4. Reading a Transparent Table via RFC (Using active session)
# Assuming you have an active session
# The session object provides an embedded RFC connection via the `.rfc` property
results = session.rfc.read_table(
table_name="T000",
fields=["MANDT", "MTEXT"],
options=["SPRAS = 'E'"]
)
print(results)
5. Fully Headless RFC Connection
For scenarios where you do not need an active SAP GUI session and want to interact purely via RFC, you can use the RfcConnection class directly.
from rpa_sap import RfcConnection
# Initialize a headless RFC connection using a context manager
with RfcConnection(
connection_string="My SAP System",
user_id="user_id",
password="password",
client="100",
language="EN"
) as rfc:
# Read a transparent table
results = rfc.read_table("T000")
print(results)
# The connection is automatically closed when the block exits
6. Executing a BAPI via RFC
You can execute BAPI functions cleanly and extract exactly the parameters or tables you need.
from rpa_sap import RfcConnection
with RfcConnection(
connection_string="My SAP System",
user_id="user_id",
password="password"
) as rfc:
results = rfc.call_bapi(
bapi_name="BAPI_USER_GET_DETAIL",
import_params={"USERNAME": "USERNAME"},
extract_imports=["ADDRESS"],
extract_tables=["ACTIVITYGROUPS"]
)
# Access the returned structures and tables
address_data = results.get("ADDRESS")
roles = results.get("ACTIVITYGROUPS")
print(f"User Full Name: {address_data.get('FULLNAME')}")
print(f"Number of roles: {len(roles)}")
7. Working with Table Controls
from rpa_sap.lib.GuiTableControl import GuiTableControl
from rpa_sap.lib.data_extractors import GuiTableControlExtractor
# Initialize the TableControl helper
table = GuiTableControl(session)
extractor = GuiTableControlExtractor(table)
# Extract the entire Table Control to a Pandas DataFrame
df = extractor.to_dataframe("wnd[0]/usr/tblSAPMV13ATCTRL_FAST_ENTRY")
print(df.head())
# You can also export directly to files
extractor.to_csv("wnd[0]/usr/tblSAPMV13ATCTRL_FAST_ENTRY", "table_control.csv")
# Set a specific cell value
table.set_cell_value(
field_id="wnd[0]/usr/tblSAPMV13ATCTRL_FAST_ENTRY",
value="100",
absolute_row_index=0,
column_title="Order Quantity"
)
8. Automating SAP Queries (SQ01)
from rpa_sap.lib.SQ01 import SQ01
# Initialize SQ01 helper
sq01 = SQ01(session)
# Navigate to the query, providing a user group and variant
sq01.start_query(query_name="MY_QUERY", user_group="MY_GROUP", variant_name="DEFAULT")
# Execute the query
sq01.execute_query()
# Export the results directly to a local file
sq01.to_local_file(folder_path="C:\\Exports", file_name="query_results.xls", file_type="xls")
9. Integrating via SAP OData (REST)
For modern SAP systems (like S/4HANA), OData is the preferred integration method. RPA-SAP provides an ODataClient with various authentication strategies (Basic, OAuth2, etc.) and handles CSRF tokens automatically for state-changing operations.
from rpa_sap.core.odata import ODataClient, BasicAuthStrategy
# 1. Choose your authentication strategy
auth = BasicAuthStrategy("USERNAME", "password")
# Or use OAuth2: auth = OAuth2Strategy("my-bearer-token")
# 2. Initialize the client
client = ODataClient("https://mysap.example.com/sap/opu/odata/sap/API_USER_SRV", auth)
# 3. Query an EntitySet and get a Pandas DataFrame
df = client.get_dataframe("UserSet", select=["UserID", "FullName"], top=50)
print(df.head())
# 4. Create a new Entity (CSRF token is fetched automatically)
new_user = {"UserID": "NEW_RPA", "FullName": "RPA Bot User"}
response = client.post("UserSet", payload=new_user)
print("Created:", response)
Testing
The project uses pytest and features a two-tier testing strategy:
-
Unit Tests (Fast & CI-Friendly): Located in
tests/unit/. These tests mock the SAP GUI COM objects and run without requiring a live SAP installation or active connection.uv run pytest tests/unit
-
Integration Tests (Live SAP Environment): Located in
tests/integration/. These tests connect to a live SAP environment and require SAP GUI to be installed, running, and accessible. They are marked with@pytest.mark.integration.uv run pytest -m "integration"
Changelog & Recent Updates
- Stability Fix: Fixed
Windows Fatal COM exceptions (0x80010108, 0x800706ba)that occurred on session closure. The library now explicitly detaches COM proxies and forces garbage collection before terminating the SAP logon process. - Type Safety: Full codebase audit using
pyrefly. Resolved all static analysis errors, standardizing type hints and dependency injection (BaseMixin) across core components. - Test Discoverability: Improved pytest integration with IDEs (like VSCode) by gracefully skipping module imports (
pytest.importorskip) during test collection when dependencies are missing.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
Contributions are welcome! Please read the contributing guidelines for more details.
Contact
For any questions or suggestions, feel free to open an issue on the GitHub repository.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file rpa_sap-2.0.2.tar.gz.
File metadata
- Download URL: rpa_sap-2.0.2.tar.gz
- Upload date:
- Size: 30.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
77644421f1f48e202847e7418ae69068a59775a03c6e422fc859fa2f0a559ba9
|
|
| MD5 |
a59a2ae9f1325477028c5519639957ac
|
|
| BLAKE2b-256 |
d22e798018057d480641213c026e83896320edb82382920dcd60da7521b65206
|
File details
Details for the file rpa_sap-2.0.2-py3-none-any.whl.
File metadata
- Download URL: rpa_sap-2.0.2-py3-none-any.whl
- Upload date:
- Size: 29.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bd26bd5e870ed354d407429e1e826b137f98ecc01a65532155dcd1e19771809d
|
|
| MD5 |
c9e00c435e094835d1af467e297c015d
|
|
| BLAKE2b-256 |
05b070a2330079f22f0a23acc9b02f4e583e1a10ea3d489f995affd570707554
|