你好,我想要做的是运行一个 python 脚本,当脚本运行时,我在 VB.NET 的文本框中显示输出,所以我不会等到脚本完成时,它正在运行。
问问题
1784 次
1 回答
2
如果您的 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
于 2012-09-12T12:51:41.457 回答