我一直在寻找一些在我的delphi代码中调用python函数(使用Python4Delphi)的方法,而不直接需要TPythonEngine.ExecStrings执行。
我的基本想法是加载一个模块,例如,
example.py
看起来像:
def DoExample(pStr: str) -> str:
pStr = "Example: " + pStr
return pStr
并这样称呼它(免责声明:我想要的行为示例,而不是实际的 P4D 行为):
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}
我也可以通过调整
example.py
来实现我的目标:
import sys
def DoExample(pStr: str) -> str:
pStr = "Example: " + pStr
return pStr
DoExample(sys.argv[1])
并像在 cli 中那样调用它,仍然需要获取其结果。
我仔细阅读了演示,但没有找到解决我问题的合理答案。也没有进一步阅读的文档(或者至少我找不到它)。
而且由于缺乏文档,我不知道这种方法是否可行。
tl;博士 我想加载一个 python 脚本,获取其定义的函数之一,在 delphi 中调用它并将其结果检索到变量中。
提前致谢!新年快乐。
Delphi-Praxis 论坛上 pyscripter 的回答:
var SL := TStringList.Crete;
try
SL.LoadFromFile('example.py');
PyEngine.ExecStrings(SL);
var Res := MainModule.DoExample('input');
finally
SL.Free;
end;