Jump to content
araujoarthur

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

Recommended Posts

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).

 

I don't know if this approach is possible due to lack of documentation so I'm looking for comments from people more familiar with the library.

 

Question was originally posted in StackOverflow.

 

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.|

Share this post


Link to post

How about?

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

 

  • Thanks 1

Share this post


Link to post
19 hours ago, pyscripter said:

How about?


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

 

Lmao I wasn't expecting an answer from you. So based on your answer I can't (and don't need) to load individual functions? I assume MainModule is in the tree of PyEngine, how would this work in case of a package with multiple modules?

Thanks for your answer.

Share this post


Link to post

The sample code above uses VarPyth for high level access to python objects.

 

MainModule is custom variant wrapping the __main__ python module.   Unless you provide optional parameters to ExecStrings, the code is executed in the context of the __main__ module.

  • Like 1
  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×