Skip to content

Commit 739170f

Browse files
committed
Add example on calling external Python code
1 parent a8ff45d commit 739170f

File tree

1 file changed

+48
-3
lines changed

1 file changed

+48
-3
lines changed

UsersGuide/source/interop_c_python.rst

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,55 @@ And plot the results:
7171
x
7272
y
7373
74-
Calling Python Code
75-
-------------------
74+
Calling external Python Code from a Modelica model
75+
--------------------------------------------------
76+
77+
The following calls external Python code through a very simplistic
78+
external function (no data is retrieved from the Python code).
79+
By making it a dynamically linked library, you might get the code to
80+
work without changing the linker settings.
81+
82+
.. omc-loadstring ::
83+
84+
function pyRunString
85+
input String s;
86+
external "C" annotation(Include="
87+
#include <Python.h>
88+
89+
void pyRunString(const char *str)
90+
{
91+
Py_SetProgramName(\"pyRunString\"); /* optional but recommended */
92+
Py_Initialize();
93+
PyRun_SimpleString(str);
94+
Py_Finalize();
95+
}
96+
");
97+
end pyRunString;
98+
99+
model CallExternalPython
100+
algorithm
101+
pyRunString("
102+
print 'Python says: simulation time',"+String(time)+"
103+
");
104+
end CallExternalPython;
105+
106+
.. omc-mos ::
107+
:erroratend:
108+
109+
system("python-config --cflags > pycflags")
110+
system("python-config --ldflags > pyldflags")
111+
pycflags := stringReplace(readFile("pycflags"),"\n","");
112+
pyldflags := stringReplace(readFile("pyldflags"),"\n","");
113+
setCFlags(getCFlags()+pycflags)
114+
setLinkerFlags(getLinkerFlags()+pyldflags)
115+
simulate(CallExternalPython, stopTime=2)
116+
117+
Calling OpenModelica from Python Code
118+
-------------------------------------
76119

77120
This section describes a simple-minded approach to calling Python code
78121
from OpenModelica. For a description of Python scripting with
79-
OpenModelica, see Chapter 13.
122+
OpenModelica, see :ref:`ompython`.
80123

81124
The interaction with Python can be perfomed in four different ways
82125
whereas one is illustrated below. Assume that we have the following
@@ -151,3 +194,5 @@ compiler via this interface.
151194

152195
The fourth variant is to use external function calls to directly
153196
communicate with the executing simulation process.
197+
198+
.. omc-reset ::

0 commit comments

Comments
 (0)