gpt4 book ai didi

vb.net - 读取控制台进程输出

转载 作者:行者123 更新时间:2023-12-04 23:06:53 28 4
gpt4 key购买 nike

我正在尝试使用以下代码读取控制台进程的完整内容(3 秒后):

Dim NewProcess As New System.Diagnostics.Process()
With NewProcess.StartInfo
.FileName = EXE_PATH
.RedirectStandardOutput = True
.RedirectStandardError = True
.RedirectStandardInput = True
.UseShellExecute = False
.WindowStyle = ProcessWindowStyle.Normal
.CreateNoWindow = False
End With

NewProcess.Start()

System.Threading.Thread.Sleep(3000)

MsgBox(NewProcess.StandardOutput.ReadToEnd)

但是,应用程序在尝试“ReadToEnd”时似乎暂停,我认为这是因为控制台进程是一个连续的输出并且永远不会真正结束。 'ReadLine' 工作正常,但只获取第一行,但在那个阶段我需要控制台的全部内容。

我怎么解决这个问题?

最佳答案

我会尝试使用 Process.OutputDataReceived 事件异步读取输出。

见:http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx#Y242

Private Shared processOutput As StringBuilder = Nothing

Public Shared Sub StartSomeProcess()
processOutput = new StringBuilder()
Dim NewProcess As New System.Diagnostics.Process()
With NewProcess.StartInfo
.FileName = EXE_PATH
.RedirectStandardOutput = True
.RedirectStandardError = True
.RedirectStandardInput = True
.UseShellExecute = False
.WindowStyle = ProcessWindowStyle.Normal
.CreateNoWindow = False
End With

' Set our event handler to asynchronously read the sort output.
AddHandler NewProcess.OutputDataReceived, AddressOf OutputHandler
NewProcess.Start()
NewProcess.BeginOutputReadLine()
NewProcess.WaitForExit()
MsgBox(processOutput.ToString())
End Sub

Private Shared Sub OutputHandler(sendingProcess As Object, outLine As DataReceivedEventArgs)
' Collect the sort command output.
If Not String.IsNullOrEmpty(outLine.Data) Then
' Add the text to the collected output.
processOutput.AppendLine(outLine.Data)
End If
End Sub

关于vb.net - 读取控制台进程输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9996709/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com