unity调用python代码,捕获控制台输出到ui面板上

文章讲述了如何在Unity中调用Python脚本,通过ProcessStartInfo和输出重定向,捕获Python的打印数据,并将这些数据直接显示在UnityUI面板上,无需使用socket通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

unity调用python代码后,想把python生成的数据内容直接传到unity内的ui面板上,但不是通过socket通信传递数据。这里直接捕获python内print到控制台的内容。


1.python部分

python代码部分直接print输出想要传递的数据

2.unity部分

传递的数据通过文本的方式被unity接收,通过字符串操作获取想要的数据

public class gtPrediction : MonoBehaviour
{
    private ProcessStartInfo startInfo;
    private Process process;
    private static StringBuilder output = new StringBuilder();
	 void Start()
    {
        Kill_All_Python_Process();
        // 创建UDP通信的Client
        udpClient = new UdpClient();
        // 设置IP地址与端口号
        remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 31412);
        localEP = new IPEndPoint(IPAddress.Any, 0);
        //string pythonPath = Application.dataPath + "/TDSTF/TDSTF-main/main.py";
        string pythonPath = "D:/main.py";
        // 创建Process
        process = new Process();
        // 创建ProcessStartInfo对象
        startInfo = new ProcessStartInfo();
        process.StartInfo = startInfo;
        // 设定执行cmd
        //startInfo.FileName = @"E:/DTprediction/Library/PythonInstall/python.exe";
        startInfo.FileName = Application.dataPath + "/StreamingAssets/PythonInstall/python.exe";
        // 输入参数是上一步的command字符串
        startInfo.Arguments = pythonPath;
        // 因为嵌入Unity中后台使用,所以设置不显示窗口
        startInfo.CreateNoWindow = true;
        // 这里需要设定为false
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardInput = true;     //打开流输入
        // 设置重定向这个进程的标准输出流,用于直接被Unity C#捕获,从而实现 Python -> Unity 的通信
        startInfo.RedirectStandardOutput = true;
        // 设置重定向这个进程的标准报错流,用于在Unity的C#中进行Debug Python里的bug
        startInfo.RedirectStandardError = true;
        //process.StandardInput.AutoFlush = true;//每次调用 Write()之后,将其缓冲区刷新到基础流
        process.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
        process.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived);

        //启动脚本Process,并且激活逐行读取输出与报错
        process.Start();
        process.BeginErrorReadLine();
        process.BeginOutputReadLine();
    }
    private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.Data))
        {
            output.Append(e.Data);
            UnityEngine.Debug.Log(output.ToString());
        }
    }
    private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.Data))
        {
            // 调试语句
            UnityEngine.Debug.LogError("Received error output: " + e.Data);
        }
    }

}

总结

output.ToString()就是想要的数据了,直接显示在ui即可。

代码流程解读

在这段代码中,Python 和 Unity 通过 UDP 通信 和 标准输出流(Standard Output Stream)的重定向来传递数据。具体来说,Unity 作为主程序,通过启动一个 Python 进程执行脚本,并在 Unity 中捕获 Python 的输出和错误信息,以实现两者之间的数据传递和实时通信。
数据传递过程分析:

  1. 通过 UDP 发送数据
    代码中的 UdpClient 被创建并绑定到 Unity 程序的 gtPrediction 类上。
    remoteEP 和 localEP 分别定义了 Python 和 Unity 之间的数据传递端点。这里设置的 IP 地址是 “127.0.0.1”,意味着 Unity 和 Python 进程在同一台设备上运行,通过 UDP 套接字实现数据传递
    通过 UDP 的方式,Unity 程序可以发送消息到 Python 脚本,同时也可以监听从 Python 发送的消息。
  2. 启动 Python 脚本的进程
    Process 对象被创建并设置为 startInfo 中的配置信息,主要包括:
    【FileName】:指定 Python 的可执行文件路径(即 Python 解释器路径)。
    【Arguments】:将 Python 脚本的路径作为参数传递给 Python 解释器,以启动该脚本。
    【CreateNoWindow】:设为 true 以隐藏 Python 执行的命令行窗口,使其后台运行。
    【UseShellExecute】:设为 false,以便在 Unity 中重定向标准输入/输出流。
  3. 重定向标准输出和错误流
    RedirectStandardOutput 和 RedirectStandardError 被设置为 true,使 Unity 能够捕获 Python 输出的文本数据,包括正常输出和错误信息。
    OutputDataReceived 和 ErrorDataReceived 事件通过委托方法 OnOutputDataReceived 和 OnErrorDataReceived 进行处理,从而可以实时处理来自 Python 脚本的输出内容。
  4. 实时捕获并显示 Python 的输出和错误
    OnOutputDataReceived 和 OnErrorDataReceived 函数用于接收 Python 的输出和错误信息:
    OnOutputDataReceived 会在 Python 脚本有新输出时被触发,将输出内容追加到 output 中,并通过 UnityEngine.Debug.Log 在 Unity 控制台中显示。
    OnErrorDataReceived 则用于捕获并显示 Python 脚本的错误信息,便于在 Unity 中进行调试。
    这样,通过重定向 Python 的标准输出和错误流,Unity 可以实时地接收和显示 Python 脚本的运行信息。

代码流程总结

这段代码中的 Unity 和 Python 之间的数据传递主要通过以下两种方式实现:
1.UDP 通信:用于双向数据传递。Unity 创建一个 UdpClient,与 Python 进程通过 127.0.0.1 的端口通信,可以用于发送和接收实时数据。
2.标准输出流重定向:Unity 启动并管理 Python 脚本进程,将其标准输出和错误流重定向到 Unity 中,通过 OnOutputDataReceived 和 OnErrorDataReceived 捕获并处理 Python 的输出和错误信息。
这种通信模式允许 Python 和 Unity 在同一台设备上运行,且实现了实时通信与信息反馈。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fortune56

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值