0
你好,試圖做的是運行一個python腳本,而腳本運行時我在VB.NET中的文本框中顯示輸出,所以我不等到腳本在運行時完成否。在VB.NET中顯示python進程的輸出
你好,試圖做的是運行一個python腳本,而腳本運行時我在VB.NET中的文本框中顯示輸出,所以我不等到腳本在運行時完成否。在VB.NET中顯示python進程的輸出
如果您的python腳本輸出到標準輸出流,那麼您可以通過將流程的標準輸出重定向到您的應用程序來相當容易地讀取它。當你創建一個進程時,你可以在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