How to Run a Python Script from ABAP?
I confess...
I stole wrote this note under the impression of material I read on SAP Blogs. The link to the source that impressed me is provided below:
Original Source: How To Use Python via External OS Commands and Embed the Scripts Seamlessly
So, whether to read it or not is up to you. For my part, I will provide a free translation of the material from the link above, with a few personal touches. This post can be categorized as a userhack.
What is this about?
This is about launching Python scripts from ABAP. To run the scripts, external command tools are used. The original author claims that running external commands using FM SXPG_COMMAND_EXECUTE
is not a good practice — and it's hard to disagree. But the approach discussed here doesn’t aim to follow best practices.
Python Distribution
You need to install or copy a Python distribution onto the application server where your SAP system is deployed.
Defining an External Command
Use transaction SM69 to define an external command.
See Maintaining External Commands
Defining Logical and Physical File Paths
See: Setting Platform-Independent File Names
Also refer to the documentation at the following SPRO path:
IMG: SAP NetWeaver → Application Server → System Administration → Platform-Independent File Names
Define the physical path where the Python script will be placed on the application server via transaction FILE.
You’ll also need to define parameters for the new logical file.
See: Logical File Names
Creating an ABAP Include with Python Code
Create an include that contains the Python code. You can do this using transaction SE80.
See: Include Programs
Creating a FM to Run the Script
The source code of the function module (FM) is provided in the original source. When executed, the FM will create a .py
file on the application server (according to your setup), transferring the Python code from the ABAP include. Then the script is launched using FM SXPG_STEP_COMMAND_START
. If everything is done correctly, you will see a response from the Python interpreter.
After that, the script is deleted from the application server. As the author notes, there’s no need to store the scripts on the server, since they exist as includes and can be extracted and executed when needed.
Summary
First, it’s cool. Whether to use it or not is secondary. Starting flame wars about the insecurity of this approach is pointless and unproductive. The key idea of reviews like this is to show that such schemes exist, are feasible, and usable. We expand our horizons — and thank the author Stefan Schnell.