1

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.

1 Answer 1

0

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.