我将D7与Python4Delphi结合使用。在用户导入了大量py-文件之后,Python将所有这些模块缓存起来。我需要一种方法来重新启动Py引擎。这样Py“忘记”了所有用户导入的模块,而我有“干净”的Python,w/out重新启动应用程序。该怎么做呢?
发布于 2019-01-07 03:31:26
有一个演示展示了如何使用P4D在https://github.com/pyscripter/python4delphi/tree/master/PythonForDelphi/Demos/Demo34卸载/重新加载python。下面显示了创建python组件和加载不同版本python的关键方法:
procedure TForm1.CreatePythonComponents;
begin
if cbPyVersions.ItemIndex <0 then begin
ShowMessage('No Python version is selected');
Exit;
end;
// Destroy P4D components
FreeAndNil(PythonEngine1);
FreeAndNil(PythonType1);
FreeAndNil(PythonModule1);
{ TPythonEngine }
PythonEngine1 := TPythonEngine.Create(Self);
PyVersions[cbPyVersions.ItemIndex].AssignTo(PythonEngine1);
PythonEngine1.IO := PythonGUIInputOutput1;
{ TPythonModule }
PythonModule1 := TPythonModule.Create(Self);
PythonModule1.Name := 'PythonModule1';
PythonModule1.Engine := PythonEngine1;
PythonModule1.ModuleName := 'spam';
with PythonModule1.Errors.Add do begin
Name := 'PointError';
ErrorType := etClass;
end;
with PythonModule1.Errors.Add do begin
Name := 'EBadPoint';
ErrorType := etClass;
ParentClass.Name := 'PointError';
end;
{ TPythonType }
PythonType1 := TPythonType.Create(Self);
PythonType1.Name := 'PythonType1';
PythonType1.Engine := PythonEngine1;
PythonType1.OnInitialization := PythonType1Initialization;
PythonType1.TypeName := 'Point';
PythonType1.Prefix := 'Create';
PythonType1.Services.Basic := [bsRepr,bsStr,bsGetAttrO,bsSetAttrO];
PythonType1.TypeFlags :=
[tpfHaveGetCharBuffer,tpfHaveSequenceIn,tpfHaveInplaceOps,
tpfHaveRichCompare,tpfHaveWeakRefs,tpfHaveIter,tpfHaveClass,tpfBaseType];
PythonType1.Module := PythonModule1;
PythonEngine1.LoadDll;
end;该演示使用单元PythonVersions来发现已安装的python版本。
发布于 2014-01-30 18:36:37
应该足以销毁和重新创建TPythonEngine对象:
OriginalOwner := GetPythonEngine.Owner;
GetPythonEngine.Free;
TPythonEngine.Create(OriginalOwner);销毁它调用Py_Finalize,它释放由Python分配的所有内存。
或者,如果您只是使用没有VCL包装器的Python,您可能只需调用TPythonInterface对象上的TPythonInterface来获得一个新的执行环境,而不必放弃以前完成的所有操作。
https://stackoverflow.com/questions/21464102
复制相似问题