Real-time standard output/error capture for C# processes

time standard output/error capture for C# processes… here is a solution to the problem.

time standard output/error capture for C# processes

I’m developing a C# application and I need to run an external console process (such as a python script) and receive the output data of the script in real time. The python script looks like this:

import time
while 1:
    print("Hi Foo!")
    time.sleep(.3)

The following C# code prints python script output live on the C# console:

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

However, when I try to catch the output data and manually write them to the console, I fail. The solution recommended according to other posts is this, but it doesn’t work :

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() works in blocking mode, waiting for the process to exit and return all output at once. What exactly is wrong with live output capture and how do I fix it?

Solution

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

Related Problems and Solutions