问题描述:

I am trying to print the output of my process as it runs,I used https://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginerrorreadline(v=vs.110).aspx as reference,I cant figure out why it cant print the output,can anyone tell me why the stdout is not getting printed for the following code?

using System;

using System.IO;

using System.Diagnostics;

using System.Text;

using System.Text.RegularExpressions;

namespace stdout_save

{

class Program

{

private static StringBuilder netOutput = null;

private static void NetOutputDataHandler(object sendingProcess,

DataReceivedEventArgs outLine)

{

// Collect the net view command output.

if (!String.IsNullOrEmpty(outLine.Data))

{

// Add the text to the collected output.

netOutput.Append(Environment.NewLine + " " + outLine.Data);

}

}

static void Main(string[] args)

{

string python = @"C:\\Python27\python.exe";

// python app to call

string myPythonApp = @"C:\\tools\tool.py";

ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);

myProcessStartInfo.UseShellExecute = false;

myProcessStartInfo.RedirectStandardOutput = true;

myProcessStartInfo.RedirectStandardError = true;

// start python app with arguments

myProcessStartInfo.Arguments = String.Format("{0}", myPythonApp);

Process myProcess = new Process();

myProcess.StartInfo = myProcessStartInfo;

myProcess.OutputDataReceived += new DataReceivedEventHandler(NetOutputDataHandler);

netOutput = new StringBuilder();

myProcess.Start();

myProcess.BeginOutputReadLine();

Console.WriteLine(netOutput);

myProcess.WaitForExit();

myProcess.Close();

Console.ReadLine();

}

}

}

网友答案:

You're writing the output before it has a chance to be captured, swap the two lines and it should work:

// Wait for the process to exit first
myProcess.WaitForExit();
// The dump it's output
Console.WriteLine(netOutput);

Edit:

Or, if you need to output it while the command is being run, perform your output in the OutputDataReceived handler:

private static void NetOutputDataHandler(object sendingProcess,
    DataReceivedEventArgs outLine)
{
    // Collect the net view command output.
    if (!String.IsNullOrEmpty(outLine.Data))
    {
        // Add the text to the collected output.
        netOutput.Append(Environment.NewLine + "  " + outLine.Data);
        // And output it as it's sent
        Console.WriteLine(outLine.Data);
    }
}
相关阅读:
Top