IronPython内存释放问题

原始代码:

ScriptEngine eng = IronPython.Hosting.Python.CreateEngine();

优化后的代码:

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.如果需要循环调用python,不建议重复CreateEngine,运行速度会变慢,可使用下面代码生成ScriptEngine:

private ScriptEngine _eng;
public ScriptEngine eng
{
    get
    {
        if (_eng != null)
        {
            return _eng;
        }
        else
        {
            var options = new Dictionary<string, object> { ["LightweightScopes"] = true };
            _eng = Python.CreateEngine(AppDomain.CurrentDomain, options);
            return _eng;
        }
    }
    set
    {
        _eng = value;
    }
}

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

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

ScriptEngine eng
{
    get
    {
        var options = new Dictionary<string, object> { ["LightweightScopes"] = true };
        return IronPython.Hosting.Python.CreateEngine(AppDomain.CurrentDomain, options);
    }
}
posted @ 2023-08-14 13:44  新*  阅读(68)  评论(0编辑  收藏  举报