C# 了解如何使用System.Diagnostics.Process控制标准输出
我看到了一些关于如何启动进程和将数据推入stdin的问题,但没有看到如何控制它们的输出 首先,这是我当前的代码,从控制台模式C#应用程序运行:C# 了解如何使用System.Diagnostics.Process控制标准输出,c#,.net,doxygen,C#,.net,Doxygen,我看到了一些关于如何启动进程和将数据推入stdin的问题,但没有看到如何控制它们的输出 首先,这是我当前的代码,从控制台模式C#应用程序运行: // Prepare the process to run ProcessStartInfo start = new ProcessStartInfo(); // Enter in the command line arguments, everything you would enter after the executable
// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = " -";
// Enter the executable to run, including the complete path
start.FileName = "doxygen.exe";
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Normal;
start.CreateNoWindow = false;
start.RedirectStandardInput = true;
start.UseShellExecute = false;
// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
//doxygenProperties is just a dictionary
foreach (string key in doxygenProperties.Keys)
proc.StandardInput.WriteLine(key+" = "+doxygenProperties[key]);
proc.StandardInput.Close();
proc.WaitForExit();
// Retrieve the app's exit code
int exitCode = proc.ExitCode;
}
当我运行这个程序时,我没有看到任何新窗口(尽管我认为我应该看到),所有doxygen.exe的标准输出都被打印到我的应用程序的控制台窗口
我希望发生两件事中的一件:
此外,为什么我没有为派生进程获得一个单独的窗口,为什么派生进程将输出写入我的窗口不是它自己的?您可以做的一件事是使用
RedirectStandardOutput
,而不是使用WaitForExit
,您可以使用ReadToEnd
ProcessStartInfo start = new ProcessStartInfo();
start.RedirectStandardOutput = true;
//make other adjustments to start
Process p = new Process();
p.StartInfo = start;
p.Start();
string output = p.StandardOutput.ReadToEnd();
然后您可以在空闲时使用字符串输出
如果要实时获取输出,则
p.StandardOutput
属性具有允许异步获取输出的方法。我不知道它的所有细节,我以前只使用过一次,但是如果你搜索的话,那里有大量的文献
同时重定向
标准输出
和标准错误
时也要小心,如果它们足够长,可能会导致死锁 您需要做两件事:
1) 通过在流程中将属性设置为true,指示您希望将流程的标准输出定向到应用程序
2) 在调用WaitForExit
之前,开始捕获输出:
string sOutput = p.StandardOutput.ReadToEnd();
如果在调用wait for exit之前没有开始读取输出,则可能会遇到死锁
但是,重要的是要知道,标准输出将只捕获输出信息,而不是写入应用程序的标准错误流的任何内容
为了捕获这两个信息流,您可以挂接进程和事件,并将事件数据直接写入日志文件或存储在类属性中,以便在进程完成后使用。因此您没有注意到
重定向标准输出
属性或标准输出
属性,您没有检查正在设置的属性的文档,例如CreateNoWindow
,它专门说明是否显示窗口?文档的存在是有原因的。此外,重定向输出也被讨论了很多;我发现很难相信你花了很长时间找到关于这个主题的讨论。文档()太糟糕了。它给出了这些事情的一行解释,但没有解释它们的实际含义。例如,为什么没有基于我的设置出现新窗口,为什么派生进程的stdout出现在我的应用程序窗口中,而不是它自己的窗口中?一点也不可怕。的文档包含多段文本和多个代码示例。您似乎认为文档很糟糕,甚至连看都没看。@Servy文档解释了如何捕获标准输出,它正好回答了我问题的一部分:第2点。我看不到任何解释,为什么派生进程在没有任何重定向的情况下将stdout写入我的应用程序的stdout,或者为什么即使我设置了start.WindowStyle=ProcessWindowStyle.Normal,派生的应用程序也没有显示新窗口;start.CreateNoWindow=false代码>