IronPython内存释放问题

七年新 / 2023-08-14 / 原文

先给出优化后的代码:

var options = new Dictionary<string, object> { ["LightweightScopes"] = true };
ScriptEngine eng = IronPython.Hosting.Python.CreateEngine(AppDomain.CurrentDomain, options);
var scope = eng.CreateScope();
using (var streamOut = new MemoryStream())
{
    ICollection<string> Paths = eng.GetSearchPaths();
    Paths.Add(Environment.CurrentDirectory + @"\Lib");
    Paths.Add(Environment.CurrentDirectory + @"\Lib\site-packages");
    eng.SetSearchPaths(Paths);
    eng.Runtime.IO.SetOutput(streamOut, Encoding.ASCII);
    var pycode="the python code you need execute";//你需要执行的python代码
    eng.Execute(pycode, scope);
    string printS = Encoding.UTF8.GetString(streamOut.ToArray());//python代码执行的print输出结果
    eng.Runtime.Shutdown();
}

注意:

1.GC.Collect()对此处内存回收作用不大。

2.如果通过get的方式获取ScriptEngine ,会造成无法获取python的输出结果(也就是上面代码的printS为空),原因未知。

如:

ScriptEngine eng
{
    get
    {
        var options = new Dictionary<string, object> { ["LightweightScopes"] = true };
        return IronPython.Hosting.Python.CreateEngine(AppDomain.CurrentDomain, options);
    }
}

3.调用eng.Runtime.Shutdown();关闭ScriptEngine的Runtime。