2016-07-11 12 views
-1

実行中のプロセスの出力を印刷しようとしていますが、参考のためにhttps://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginerrorreadline(v=vs.110).aspxを使用しました。なぜ出力が印刷できないのかわかりません。なぜstdoutが次のコードのために印刷されていますか?それは撮影する機会を持って前に出力を書いている、2行を入れ替え、それが動作するはずプロセスが出力されないプロセスの出力

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

私の質問に何が問題なのですか?-1'ededという理由を追加してください。 –

答えて

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

Anon - プロセスが終了すると出力を出力します。実行時に出力を取得しようとしています –

+0

Ahh、データを取得するときに出力する必要があります。私の編集を参照してください。 –

関連する問題