Python.NET执行代码后程序卡住无法退出,求助排查原因
问题分析与解决方案
你的代码缺少Python.NET引擎的资源清理步骤——在调用PythonEngine.Initialize()初始化Python运行时后,必须调用PythonEngine.Shutdown()来释放相关资源,否则进程会因资源未正常回收而挂起,无法正常退出。这个问题在M1这类ARM架构的Mac系统上表现得尤为明显。
修改后的代码如下:
using System; using Python.Runtime; Console.WriteLine("Executing python..."); PythonEngine.Initialize(); try { // acquire the GIL before using the Python interpreter using (Py.GIL()) { // create a Python scope using (var scope = Py.CreateScope()) { string code = @" x = 1+3 print(x) "; scope.Exec(code); } } } finally { // 强制清理Python引擎资源,确保进程正常退出 PythonEngine.Shutdown(); } Console.WriteLine("Finish");
使用try-finally块可以保证即使代码执行过程中出现异常,PythonEngine.Shutdown()也能被执行,彻底避免资源泄漏导致的进程挂起问题。
内容的提问来源于stack exchange,提问作者Bharata
相关产品推荐
相关产品推荐

