CloudBuilder.Topshelf/Python/PythonCommand.cs
owenchen 527205520b ow
2026-05-29 13:03:00 +08:00

91 lines
2.5 KiB
C#

using CloudBuilder.Core.DatabaseAccessor.Entity;
using Python.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CloudBuilder.Topshelf.Python
{
public class PythonCommand
{
private bool _disposed = false; // 释放标记
public dynamic PythonCreateScope { get; set; }
public IApplicationService ApplicationService;
public PythonCommand(IApplicationService applicationService)
{
ApplicationService = applicationService;
Runtime.PythonDLL = applicationService.Configuration["Python:PythonCommand"];
PythonEngine.PythonHome = Path.GetDirectoryName(Runtime.PythonDLL);
PythonEngine.Initialize();
PythonCreateScope = Py.CreateScope();
}
public void Exec(string arg)
{
using (Py.GIL())
{
PythonCreateScope.Exec(arg);//"from pyhanlp import HanLP"
}
}
public string GetValueExec(string arg)
{
using (Py.GIL())
{
PythonCreateScope.Exec(string.Format("s_value={0}", arg));
var value = PythonCreateScope.Eval("s_value");
return value.ToString();
}
}
public string[] GetValuesExec(string arg)
{
using (Py.GIL())
{
PythonCreateScope.Exec(string.Format("s_list={0}", arg));
var value = PythonCreateScope.Eval("s_list");
string[] st = value.As<string[]>();
return st;
}
}
// 核心:释放 Python.NET 资源
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this); // 阻止析构函数重复执行
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
// 1. 释放 Python 作用域
if (PythonCreateScope != null)
{
PythonCreateScope.Dispose();
PythonCreateScope = null;
}
// 2. 关闭 Python 运行时(关键!)
if (PythonEngine.IsInitialized)
{
AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true);
PythonEngine.Shutdown(); // 销毁 Python 解释器
}
_disposed = true;
}
}
}