如何逐行读取标准输出线? [英] How to read standard output line by line?
问题描述
我要检查从生产线的标准输出线。读取第二行myProcess.StandardOutput.EndofStream改变从假变为真之后。因此,它从while循环退出。 ?也许我应该用别的东西。
过程myProcess =新工艺();
试
{
myProcess.StartInfo.UseShellExecute = FALSE;
myProcess.StartInfo.FileName = my_command;
myProcess.StartInfo.Arguments =+位置;
myProcess.StartInfo.CreateNoWindow = TRUE;
myProcess.StartInfo.RedirectStandardOutput = TRUE;
myProcess.Start();
在
{
串standard_output = myProcess.StandardOutput.ReadLine()(myProcess.StandardOutput.EndOfStream!);
如果(standard_output.Contains(XX))
{
//做些什么
中断;
}
}
myProcess.WaitForExit();
}
这StandardOutput读数不像从具有明确的端点的文件中读取。钩住StandardOutput一个StreamReader可以达到EndOfStream在进程退出之前(即所有可用的输出被读取)。
不过的ReadLine,会等到数据可用,或流被关闭。当流被关闭,的ReadLine将返回null
重写你的主循环中使用的阻断我的ReadLine / O的作为等待条件:
字符串standard_output;
,而((standard_output = myProcess.StandardOutput.ReadLine())!= NULL)
{
如果(standard_output.Contains(XX))
{
//做些什么
中断;
}
}
I want to inspect line by line standard output from process. after reading the second line myProcess.StandardOutput.EndofStream change from false to true. Hence it quits from while loop. Maybe I should use something else?
Process myProcess = new Process();
try
{
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = my_command;
myProcess.StartInfo.Arguments = " "+ location;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.Start();
while (!myProcess.StandardOutput.EndOfStream)
{
string standard_output = myProcess.StandardOutput.ReadLine();
if (standard_output.Contains("xx"))
{
//do something
break;
}
}
myProcess.WaitForExit();
}
Reading from StandardOutput isn't like reading from a file that has a definite endpoint. A StreamReader hooked to StandardOutput can reach EndOfStream (meaning all available output has been read) before the process exits.
ReadLine however, will wait until data is available or the stream is closed. When the stream is closed, ReadLine will return null.
Rewriting your main loop to use the blocking I/O of ReadLine as the wait condition:
string standard_output;
while ((standard_output = myProcess.StandardOutput.ReadLine()) != null)
{
if (standard_output.Contains("xx"))
{
//do something
break;
}
}
这篇关于如何逐行读取标准输出线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!