2014-09-17 3 views
0

저는 파이썬 스크립트 출력을 읽고 텍스트 상자에 결과를 보여주는 프로그램을 작성하고 있습니다. 오랜 시간 동안 스크립트를 실행 했으므로 출력을 1 초마다 (또는 각 줄을 기록한 후) 볼 수 있기를 원합니다. 이제 프로세스가 끝날 때만 출력을 볼 수 있습니다. 누군가가 문제를 알고 있습니까? 내 코드의cmd 출력을 실시간으로 읽는 중

조각 :

Process p = new Process(); 
p.StartInfo.CreateNoWindow = true; 
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
p.OutputDataReceived += new DataReceivedEventHandler (p_OutputDataReceived); 
p.ErrorDataReceived += new DataReceivedEventHandler (p_ErrorDataReceived); 
p.Exited += new EventHandler (p_Exited); 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.RedirectStandardError = true; 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.FileName = "python.exe"; 
p.StartInfo.Arguments = "path " + commandline; 
p.Start(); 
StreamReader s = p.StandardOutput; 
String output = s.ReadToEnd(); 
textBox3.Text = output; 
p.WaitForExit(); 

답변

2

나는 내 자신의 프로그램에 그것을 다음과 같은 방법을하고 있어요 :

private static void startProgram(
    string commandLine) 
{ 
    var fileName = commandLine; 
    var arguments = string.Empty; 
    checkSplitFileName(ref fileName, ref arguments); 

    var info = new ProcessStartInfo(); 
    info.FileName = fileName; 
    info.Arguments = arguments; 

    info.UseShellExecute = false; 
    info.RedirectStandardOutput = true; 
    info.RedirectStandardError = true; 

    using (var p = new Process()) 
    { 
     p.StartInfo = info; 
     p.EnableRaisingEvents = true; 

     p.OutputDataReceived += (s,o) => { 
      Console.WriteLine(o.Data); 
     }; 
     p.Start(); 

     p.BeginOutputReadLine(); 

     p.WaitForExit(); 
    } 
} 

즉, OutputDataReceived event에 가입하고 BeginOutputReadLine method으로 전화를 걸었습니다. this similar Stack Overflow question을 참조하십시오.

1

(내 위의 소스 코드 can be found here의 방법 checkSplitFileName)

는 전 C#에서 내 파이썬 스크립트를 실행이 같은 문제가 있었다. 문제는 파이썬이 stdout (print())의 결과를 버퍼링한다는 것입니다.

여기서 두 가지 중 하나를 수행 할 수 있습니다.

출력을 세척하기 위해 모든 print() 라인 후 파이썬 스크립트에 다음을 추가합니다.

실행 -u 명령 줄 매개 변수를 사용하여 파이썬 컴파일러

import sys 
print('Hello World!') 
sys.stdout.flush() 

. 이렇게하면 인쇄 할 때마다 위의 플러시 라인을 추가 할 필요가 없습니다.

... 
p.StartInfo.FileName = "cmd.exe"; 
p.StartInfo.Arguments = "python.exe -u path " + commandline; 
... 
관련 문제