C# Capturing Python.exe Output And Displaying It In Textbox
Solution 1:
I just ran into this question myself, and after a ton of experimenting, what worked for me was running the python process with the "-u" option, which makes the output unbuffered. With that, everything worked completely fine.
Solution 2:
I ran into this problem while making a MiniConsole exactly for that purpose.
I used your technique with
pro.EnableRaisingEvents = true;
pro.OutputDataReceived +=newDataReceivedEventHandler(OnDataReceived);
pro.ErrorDataReceived +=newDataReceivedEventHandler(OnDataReceived);
The strange thing is that all the output was coming from ErrorDataReceived instead of OutputDataReceived (with valid commands).
So I think you're missing:
pro.BeginErrorReadLine();
Also I was starting the process in the main thread (I don't have any worker), using python27.
Here is the full start:
// executable: "c:\\python27\\python.exe", arguments: "myscript.py"ProcessStartInfostartInfo=newProcessStartInfo(executable, arguments);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.WorkingDirectory = textBoxWorkingDirectory.Text;
try
{
Processp=newProcess();
p.StartInfo = startInfo;
p.EnableRaisingEvents = true;
p.OutputDataReceived += newDataReceivedEventHandler(OnDataReceived);
p.ErrorDataReceived += newDataReceivedEventHandler(OnDataReceived);
p.Exited += newEventHandler(OnProcessExit);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
Solution 3:
I remember having a similar issue a while back and I think I did something similar to this in my .py scripts instead of using the print
function:
sLog = 'Hello World!'
subprocess.Popen( 'echo ' + sLog, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True )
Not sure if I set the shell
parameter to True
or False
though. Also not sure about all the "std" parameters. You might want to experiment a bit there.
Solution 4:
If you're starting the Python process from your code, then THIS will make your life really easy and I think it's about the cleanest way to go.
Post a Comment for "C# Capturing Python.exe Output And Displaying It In Textbox"