1

I'm trying to maintain a connection between a C# and a Python script. I want to read the output from python at the same moment it is printed, but I can do it once the python script is finished, not during its execution.

Here is the C# program, which read asynchronously the stdout stream.

using System;
using System.Diagnostics;

namespace PruebaConnexion
{
    class Program
    {
        static void Main(string[] args)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = "D:\\Programas\\Anaconda\\python.exe";
            start.Arguments = ".\\PythonScript.py";
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            // start.RedirectStandardInput = true;

            Process process = Process.Start(start);
            process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                Console.WriteLine("Hello "+e.Data);
            });

            process.BeginOutputReadLine();

            while (true)
            {}
            
        }
    }
}

And here is the python code:

import time
import sys

for i in range(10):
    time.sleep(1)

    sys.stdout.write("OK")

I also tried with print, instead of sys.stdout.write. I get printed on C#:

Hello OKOKOKOKOKOKOKOKOKOK

But what I need is:

Hello OK
Hello OK
Hello OK
.
.

One Hello OK per second, but not all of them at the same time.

1 Answers1

0

I also tried with print, instead of sys.stdout.write. I get printed on C#:

I tested with sys.stdout.write and got same result, but it worked as expected with print. I am using python3 on WSL. I also got it to work like this:

sys.stdout.write("OK\n")

So it seems like c# will read the data line by line

toftis
  • 1,070
  • 9
  • 26