[英]How to capture a Processes STDOUT and STDERR line by line as they occur, during process operation. (C#)
I am going to execute a Process (lame.exe) to encode a WAV file to MP3. 我将执行一个进程(lame.exe)将WAV文件编码为MP3。
I want to process the STDOUT and STDERR of the process to display progress information. 我想处理进程的STDOUT和STDERR以显示进度信息。
Do I need to use threading? 我需要使用线程吗? I can't get my head around it.
我无法理解它。
Some simple example code would be appreciated. 一些简单的示例代码将不胜感激。
Thanks 谢谢
If running via the Process
class, you can redirect the streams so you may process them. 如果通过
Process
类运行,则可以重定向流以便可以处理它们。 You can read from stdout or stderr synchronously or asynchronously. 您可以同步或异步读取stdout或stderr。 To enable redirecting, set the appropriate redirection properties to
true
for the streams you want to redirect (eg, RedirectStandardOutput
) and set UseShellExecute
to false
. 要启用重定向,请为要重定向的流(例如,
RedirectStandardOutput
)将相应的重定向属性设置为true
,并将UseShellExecute
设置为false
。 Then you can just start the process and read from the streams. 然后你就可以开始这个过程并从流中读取。 You can also feed input redirecting stdin.
您还可以输入重定向标准输入的输入。
eg, Process and print whatever the process writes to stdout synchronously 例如,处理并打印进程同步写入stdout的任何内容
var proc = new Process()
{
StartInfo = new ProcessStartInfo(@"SomeProcess.exe")
{
RedirectStandardOutput = true,
UseShellExecute = false,
}
};
if (!proc.Start())
{
// handle error
}
var stdout = proc.StandardOutput;
string line;
while ((line = stdout.ReadLine()) != null)
{
// process and print
Process(line);
Console.WriteLine(line);
}
You should be able to listen to the STDOUT with the Process.OutputDataReceived
event. 您应该能够使用
Process.OutputDataReceived
事件监听STDOUT。 There is an example on the MSDN page. MSDN页面上有一个示例。 There is also an
Process.ErrorDataReceived
event for STDERR. STDERR还有一个
Process.ErrorDataReceived
事件。
There is an MSDN example for this... Here is a simplified version: 有一个MSDN示例 ...这是一个简化版本:
var StdOut = "";
var StdErr = "";
var stdout = new StringBuilder();
var stderr = new StringBuilder();
var psi = new ProcessStartInfo();
psi.FileName = @"something.exe";
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
var proc = new Process();
proc.StartInfo = psi;
proc.OutputDataReceived += (sender, e) => { stdout.AppendLine(e.Data); };
proc.ErrorDataReceived += (sender, e) => { stderr.AppendLine(e.Data); };
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit(10000); // per sachin-joseph's comment
StdOut = stdout.ToString();
StdErr = stderr.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.