output of a process not getting printed

时间:2016-07-11 23:25:59

标签: c#

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

1 个答案:

答案 0 :(得分:1)

您在输出有机会被捕获之前编写输出,交换两行并且应该有效:

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

修改

或者,如果您需要在运行命令时输出它,请在OutputDataReceived处理程序中执行输出:

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