【问题标题】:.NET Intercepted STDOUT from Python is always empty in Unity.NET 从 Python 中截获的 STDOUT 在 Unity 中始终为空
【发布时间】:2020-01-22 14:50:13
【问题描述】:

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

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()

但是,即使我用SYNCstdout 发送垃圾邮件,C# 端也没有出现任何内容。但是,当从 shell 运行时,它会出现在命令提示符中。

Python 代码

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

【问题讨论】:

  • 为什么不只是sys.stdout.write(b"SYNC\n")
  • 我一直在尝试不同的 IPC 机制,它们都偶然使用write() 作为它们的写入函数,例如管道和套接字。

标签: c# python unity3d process ipc


【解决方案1】:

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

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();
}

它会异步读取输出

取自https://stackoverflow.com/a/29753402/1744164

test.py

import sys

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

【讨论】:

  • 如果可能,我想同步执行此操作。
  • 看我给你的链接,有同步和异步的例子
  • 哦,你是对的。我没看到。无论哪种方式:两种方法都没有返回任何内容。
  • 好吧,一个 void 方法将返回 void 实际上是 nothing
  • 我测试了上面的代码,它按预期工作,我也会添加python代码。你忘了import sys 吗?没有那条线,我只会在错误输出上得到一个输出
猜你喜欢
  • 1970-01-01
  • 2019-01-25
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多