从.NET应用程序捕获控制台输出(C#)

如何从.NET应用程序调用控制台应用程序并捕获控制台中生成的所有输出?

(请记住,我不想先将这些信息保存在一个文件中,然后重新保存,因为我希望将它作为现场直播。)

这可以很容易地使用ProcessStartInfo.RedirectStandardOutput属性来实现。 完整的示例包含在链接的MSDN文档中; 唯一需要注意的是,您可能必须redirect标准错误stream以查看应用程序的所有输出。

Process compiler = new Process(); compiler.StartInfo.FileName = "csc.exe"; compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs"; compiler.StartInfo.UseShellExecute = false; compiler.StartInfo.RedirectStandardOutput = true; compiler.Start(); Console.WriteLine(compiler.StandardOutput.ReadToEnd()); compiler.WaitForExit(); 

创build控制台进程时,使用ProcessInfo.RedirectStandardOutput来redirect输出。

然后你可以使用Process.StandardOutput来读取程序输出。

第二个链接有一个示例代码如何做到这一点。

这比@mdb接受的答案有点改进。 具体来说,我们也捕获过程的错误输出。 此外,我们通过事件捕获这些输出,因为如果要捕获错误和常规输出,则ReadToEnd()不起作用。 我花了一段时间来完成这个工作,因为它实际上还需要Start()之后的BeginxxxReadLine()调用。

 using System.Diagnostics; Process process = new Process(); void LaunchProcess() { process.EnableRaisingEvents = true; process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived); process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived); process.Exited += new System.EventHandler(process_Exited); process.StartInfo.FileName = "some.exe"; process.StartInfo.Arguments = "param1 param2" process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); //below line is optional if we want a blocking call //process.WaitForExit(); } void process_Exited(object sender, EventArgs e) { Console.WriteLine(string.Format("process exited with code {0}\n", process.ExitCode.ToString())); } void process_ErrorDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data + "\n"); } void process_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data + "\n"); } 

ConsoleAppLauncher是专门为回答这个问题而开发的一个开源库。 它捕获控制台中生成的所有输出,并提供简单的界面来启动和closures控制台应用程序。

每次当控制台将新行写入标准/错误输出时,ConsoleOutput事件都会被触发。 线路排队并保证按照输出顺序。

也可作为NuGet包使用 。

示例调用以获取完整的控制台输出:

 // Run simplest shell command and return its output. public static string GetWindowsVersion() { return ConsoleApp.Run("cmd", "/c ver").Output.Trim(); } 

现场反馈样本:

 // Run ping.exe asynchronously and return roundtrip times back to the caller in a callback public static void PingUrl(string url, Action<string> replyHandler) { var regex = new Regex("(time=|Average = )(?<time>.*?ms)", RegexOptions.Compiled); var app = new ConsoleApp("ping", url); app.ConsoleOutput += (o, args) => { var match = regex.Match(args.Line); if (match.Success) { var roundtripTime = match.Groups["time"].Value; replyHandler(roundtripTime); } }; app.Run(); } 

我已经在O2平台 (开放源码项目)中添加了一些辅助方法,这些方法允许您通过控制台的输出和input轻松编写与另一个进程的交互脚本(请参阅http://code.google.com/p/o2platform/ source / browse / trunk / O2_Scripts / APIs / Windows / CmdExe / CmdExeAPI.cs )

对您也有用的可能是允许查看当前进程的控制台输出的API(在现有的控制或popup窗口中)。 有关更多详细信息,请参阅此博客文章: http : //o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/ (此博客还包含如何使用新进程的控制台输出)

增加了process.StartInfo.**CreateNoWindow** = true;timeout

 private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output) { using (Process process = new Process()) { process.StartInfo.FileName = exeName; process.StartInfo.Arguments = arguments; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.CreateNoWindow = true; process.Start(); output = process.StandardOutput.ReadToEnd(); bool exited = process.WaitForExit(timeoutMilliseconds); if (exited) { exitCode = process.ExitCode; } else { exitCode = -1; } } } 

来自PythonTR – PythonProgramcılarıDerneği,e-kitap,örnek

 Process p = new Process(); // Create new object p.StartInfo.UseShellExecute = false; // Do not use shell p.StartInfo.RedirectStandardOutput = true; // Redirect output p.StartInfo.FileName = "c:\\python26\\python.exe"; // Path of our Python compiler p.StartInfo.Arguments = "c:\\python26\\Hello_C_Python.py"; // Path of the .py to be executed