You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中使用Pythonnet异步导入Python模块时内部库异常问题求助

Unity中使用Pythonnet异步导入Python模块时内部库异常问题求助

大家好,我现在在Unity里用pythonnet集成Python功能,遇到了一个头疼的问题:发布版本里第一次加载Python模块耗时较长,所以我想用Task结合PythonEngine.BeginAllowThreads()做异步加载,避免阻塞Unity主线程。现在的情况是,有一个模块导入后能正常工作,但模块里的某个内部库表现异常,C#和Python两边都没报错,换成同步加载就一切正常。

我的C#代码如下:

using Python.Runtime;
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

namespace UnityPython
{
    public class Test : MonoBehaviour
    {
        [SerializeField] private Button _button;
        private SemaphoreSlim _semaphoreSlim;
        private static dynamic _module;
        private IntPtr? _state;
        private bool _importAsync = false;
        private static string ModuleName = "test_module";

        private void OnEnable()
        {
            _button.onClick.AddListener(TestModulLLM);
            _semaphoreSlim = new SemaphoreSlim(1, 1);
        }

        private void OnDisable()
        {
            _button.onClick.RemoveListener(TestModulLLM);
            _semaphoreSlim.Dispose();
           
        }

        private void OnApplicationQuit()
        {
             if (_state.HasValue)
            {
                PythonEngine.EndAllowThreads(_state.Value);
                Debug.Log("Release the GIL for threads.");
            }
        }

        async void Start()
        {
            Debug.Log("Start Scene");
            _state = PythonEngine.BeginAllowThreads();
            Debug.Log("Initialize the threads' GIL");
            if (_importAsync)
            {
                _module = await LoadAsync();
            }
            else
            {
                _module = Load();
            }
        }

        public async void TestModulLLM()
        {
            try
            {
                await _semaphoreSlim.WaitAsync();
                string result = await Task.Run(() => LLMModuleGetResult());
                Debug.Log("Result LLM: " + result);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }

        public string LLMModuleGetResult()
        {
            using (Py.GIL())
            {   
                string result = _module.main();
                return result;

            }
        }

        public static dynamic PythonLoadModule()
        {   
            using (Py.GIL())
            {   
                dynamic module = Py.Import(ModuleName);
                return module;
            }
        }
        public static dynamic Load()
        {   
  
            Debug.Log($"Start the import of the sync module {ModuleName}.");
            dynamic module = PythonLoadModule();
            Debug.Log($"End the import of the sync module {ModuleName}.");
            return module;

        }

        public async Task<dynamic> LoadAsync()
        {   
            dynamic module = await Task.Run(() => {
                Debug.Log($"Start the import of the async module {ModuleName}.");
                dynamic module = PythonLoadModule();
                Debug.Log($"End the import of the async module {ModuleName}.");
                return module;
            });
            return module;
        }
    }
}

对应的Python模块test_module.py代码:

from openai import OpenAI
from langsmith import wrappers
from langsmith import traceable

import logging
import time
import os


client = wrappers.wrap_openai(OpenAI(
    api_key=os.environ["API_KEY"]
))


@traceable
def main():
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Who are you?"}])
    return response.choices[0].message.content

我已经试过几种方法试图解决这个问题,但都没有效果:

  • 试过调用BeginAllowThreads()和不调用的情况,都没能解决问题
  • 尝试过导入后重新加载模块,也没有帮助
  • 试过用Task代替Thread,问题依然存在

备注:内容来源于stack exchange,提问作者Micanroules

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 11:29:32