Search code examples
delphilazaruspython4delphi

Load a Python module and call its functions within Delphi code without ExecString


I've been looking around for some way to call python functions (using Python4Delphi) within my delphi code without direct need for TPythonEngine.ExecStrings execution.

My base idea is to load a module, for instance, example.py looking like:

def DoExample(pStr: str) -> str:
    pStr = "Example: " + pStr
    return pStr

And call it like (disclaimer: example of behavior I'd like to have, not actual P4D behavior):

MyPythonEngine := TPythonEngine.Create(nil);
{necessary version, flags and LoadDll}
MyPythonModule := TPythonModule.Create(nil);
{necessary configs again}
MyImportedFunction := {Load the DoExample somehow and store it in this variable}
ResultOfMyImportedFunction := MyImportedFunction("This is an example"); {This should be Example: This is an example}

I could also achieve my goal by adapting the example.py:

import sys

def DoExample(pStr: str) -> str:
    pStr = "Example: " + pStr
    return pStr

DoExample(sys.argv[1])

And call it like I would in cli, still need to get its result.

I've intensively read the Demos and didn't find a reasonable answer to my problem. Also no documentation for further reading (or atleast I couldn't find it).

Also I don't know if this approach is even possible due to lack of documentation.

tl;dr I'd like load a python script, take one of its defined functions, call it within delphi and retrieve its result into a varaible.

Thanks in Advance! Happy New Year.


Solution

  • Answer from pyscripter on Delphi-Praxis forum:

    var SL := TStringList.Crete;
    try
      SL.LoadFromFile('example.py');
      PyEngine.ExecStrings(SL);
      var Res := MainModule.DoExample('input');
    finally
      SL.Free;
    end;