こんにちは、何をしようとしているのかは、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 に答える