我正在开发C#应用程序,我需要运行一个外部控制台进程(例如python脚本)并实时接收该脚本的输出数据。 python脚本是这样的:
import time
while 1:
print("Hi Foo!")
time.sleep(.3)
以下C#代码在C#控制台上实时打印python脚本输出:
static void Main(string[] args)
{
using (Process process = new Process())
{
process.StartInfo.FileName = "python.exe";
process.StartInfo.Arguments = "test.py";
process.StartInfo.UseShellExecute = false;
process.Start();
process.WaitForExit();
}
}
但是,当我尝试捕获输出数据并将其手动写入控制台时,会失败。根据其他帖子推荐的解决方案是这样的,但它不起作用:
static void Main(string[] args)
{
using (Process process = new Process())
{
process.StartInfo.FileName = "python.exe";
process.StartInfo.Arguments = "test.py";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.EnableRaisingEvents = true;
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
}
process.StandardOutput.ReadToEnd()
在阻止模式下工作,等待进程退出并立即返回全部输出。实时输出捕获到底有什么问题,我该如何解决?
答案 0 :(得分:1)
using (var process = new Process())
{
process.StartInfo.FileName = @"python.exe";
process.StartInfo.Arguments = "-u test.py";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
Console.WriteLine(line);
// do something with line
}
process.WaitForExit();
Console.Read();
}