.NET 从 Python 拦截的 STDOUT 在 Unity 中始终为空

.NET Intercepted STDOUT from Python is always empty in Unity

我正在尝试使用 Python 程序将连续的信息流从一个程序发送到另一个程序,如 ,但以字节形式发送。

pythonPathpythonScript 只是脚本的文件位置,python.exe.

C#代码

public static void PythonKernel_Test() {
    Process pythonProcess = Process.Start(new ProcessStartInfo() {
        FileName = pythonPath,
        Arguments = pythonScript,
        RedirectStandardOutput = true,
        RedirectStandardInput = true,
        UseShellExecute = false,
        CreateNoWindow = true
    });
    Stream pythonStdOut = pythonProcess.StandardOutput.BaseStream;
    for (int i = 0; i < 1000; i++) {
        byte[] buffer = new byte[256];
        pythonStdOut.Read(buffer, 0, 256);
        Debug.Log(Encoding.ASCII.GetString(buffer) + Environment.NewLine + BitConverter.ToString(buffer));
    }
    pythonStdOut.Close();
}

尽管这是在 Unity 中,您可以将 Debug.Log 替换为 Console.WriteLine()

然而,即使我用 SYNC 发送垃圾邮件 stdout,C# 端也没有任何显示。但是,当 运行 from shell.

时,它会出现在命令提示符中

Python代码

w = sys.stdout.buffer
while True:
    w.write(b"SYNC\n")
    sys.stdout.flush()

这里有一个可以试用的工作示例

public static void PythonKernel_Test()
{
    var pi = new ProcessStartInfo
    {
        FileName = "python",
        Arguments = "test.py",
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true,
    };
    var pythonProcess = new Process
    {
        StartInfo = pi,
    };

    pythonProcess.OutputDataReceived+= (s,e) => 
    {
        Console.WriteLine("OUT: {0}",e.Data);
    };
    pythonProcess.ErrorDataReceived+= (s,e) => 
    {
        Console.WriteLine("ERR: {0}",e.Data);
    };

    pythonProcess.Start();
    pythonProcess.BeginOutputReadLine();
    pythonProcess.BeginErrorReadLine();
    pythonProcess.WaitForExit();
}

它将异步读取输出

取自

test.py

import sys

while True:
    sys.stdout.write(b"SYNC\n")
    sys.stdout.flush()