2016-05-16 95 views
0

我有一個問題,我需要執行一個控制檯程序,我必須在我的程序中顯示該控制檯的輸出信息。我有一個名爲「result」的字符串變量,必須存儲該信息,但始終爲空,我不知道爲什麼。誰能幫我?我把下面的代碼:從外部程序/控制檯讀取

Process p = new Process(); 
      p.StartInfo.FileName = "python"; 
      p.StartInfo.Arguments = @"C:\Users\xxx\xxx\xxx\xxx_\xxx yyy\zzz.py " + path; 
      p.StartInfo.RedirectStandardOutput = true; 
      p.StartInfo.UseShellExecute = false; 
      p.Start(); 

      StreamReader sr = p.StandardOutput; 
      p.WaitForExit(); 
      string result = sr.ReadToEnd(); 
      sr.Close(); 

      textBox1.Text = result; 

在控制檯上,我收到8382 JGK,例如,但我的結果變量始終是「」。

+0

您可能有同步問題。您可以在開始第一個過程後添加線程睡眠嗎?當你正在使用不同的進程時,你不確定當你試圖讀取它的輸出時,第一個將會完成。 – Gnqz

+0

是的,我可以,但多少時間? Thread.sleep(5000),例如? – Imrik

+0

ReadToEnd將當前位置中的所有字符讀取到流的末尾,因此您有可能在開始閱讀之前處於最後位置。 – Vegz

回答

0

你可以嘗試這樣的事情

StreamReader sr = p.StandardOutput; 
p.WaitForExit(); 
char[] result = new char[p.Length]; //or sr.BaseStream.Length 
sr.Read(result,0,(int)p.Length); // again or sr.BaseStream.Length 

看看是否數組包含任何東西。

+0

當char [] result = new char [sr.BaseStream.Length]時,它給了我一個例外;「該序列與搜索不兼容」 – Imrik

+0

試試'char [] result = new char [128];'(Tbh我不知道是否有辦法獲得你需要的長度),然後是sr。讀取(result,0,result.Length);'看看是否有任何結果(它給了128次'\ 0'使用Gimp時:P – Vegz

+0

它給了我128'\ 0',而不是我擁有的屬性結果我使用控制檯程序 – Imrik

0

我解決了!問題出在文件路徑上。我必須把它放在與「.py」文件相同的文件夾中,它工作正常。我添加了正確的一段代碼:

string python = @"C:\xxx\python.exe"; 
     string myPythonApp = "program.py"; 
     string x = @"file.jpg"; 

     ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python); 
     myProcessStartInfo.UseShellExecute = false; 
     myProcessStartInfo.RedirectStandardOutput = true; 
     myProcessStartInfo.Arguments = myPythonApp + " " + x; 

     Process myProcess = new Process(); 
     myProcess.StartInfo = myProcessStartInfo; 
     myProcess.StartInfo.CreateNoWindow = true; 
     myProcess.Start(); 
     StreamReader myStreamReader = myProcess.StandardOutput; 
     string myString = myStreamReader.ReadLine(); 
     myProcess.WaitForExit(); 
     myProcess.Close(); 
     textBox1.Text = myString;