2012-09-12 5 views

답변

1

파이썬 스크립트가 표준 출력 스트림으로 출력하는 경우 프로세스의 표준 출력을 응용 프로그램으로 리디렉션하면 상당히 쉽게 읽을 수 있습니다. 프로세스를 만들 때 출력을 리디렉션하도록 지시하는 Process.StartInfo 객체의 속성을 설정할 수 있습니다. 그런 다음 새 출력을 수신 할 때 프로세스 객체가 발생시킨 OutputDataReceived 이벤트를 통해 비동기 적으로 프로세스의 출력을 읽을 수 있습니다. 예를 들어

,이 같은 클래스를 생성하는 경우 :

Public Class CommandExecutor 
    Implements IDisposable 

    Public Event OutputRead(ByVal output As String) 

    Private WithEvents _process As Process 

    Public Sub Execute(ByVal filePath As String, ByVal arguments As String) 
     If _process IsNot Nothing Then 
      Throw New Exception("Already watching process") 
     End If 
     _process = New Process() 
     _process.StartInfo.FileName = filePath 
     _process.StartInfo.UseShellExecute = False 
     _process.StartInfo.RedirectStandardInput = True 
     _process.StartInfo.RedirectStandardOutput = True 
     _process.Start() 
     _process.BeginOutputReadLine() 
    End Sub 

    Private Sub _process_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles _process.OutputDataReceived 
     If _process.HasExited Then 
      _process.Dispose() 
      _process = Nothing 
     End If 
     RaiseEvent OutputRead(e.Data) 
    End Sub 

    Private disposedValue As Boolean = False 
    Protected Overridable Sub Dispose(ByVal disposing As Boolean) 
     If Not Me.disposedValue Then 
      If disposing Then 
       If _process IsNot Nothing Then 
        _process.Kill() 
        _process.Dispose() 
        _process = Nothing 
       End If 
      End If 
     End If 
     Me.disposedValue = True 
    End Sub 

    Public Sub Dispose() Implements IDisposable.Dispose 
     Dispose(True) 
     GC.SuppressFinalize(Me) 
    End Sub 
End Class 

그런 다음이처럼 사용할 수 있습니다

Public Class Form1 
    Private WithEvents _commandExecutor As New CommandExecutor() 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     _commandExecutor.Execute("MyPythonScript.exe", "") 
    End Sub 

    Private Sub _commandExecutor_OutputRead(ByVal output As String) Handles _commandExecutor.OutputRead 
     Me.Invoke(New processCommandOutputDelegate(AddressOf processCommandOutput), output) 
    End Sub 

    Private Delegate Sub processCommandOutputDelegate(ByVal output As String) 
    Private Sub processCommandOutput(ByVal output As String) 
     TextBox1.Text = TextBox1.Text + output 
    End Sub 

    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed 
     _commandExecutor.Dispose() 
    End Sub 
End Class 
관련 문제