我该如何在我的.NET应用程序中调用控制台应用程序并捕获控制台生成的所有输出?
(记住,我不想先将信息保存在文件中,然后再重新列出,因为我希望能够实时接收它。)
我该如何在我的.NET应用程序中调用控制台应用程序并捕获控制台生成的所有输出?
(记住,我不想先将信息保存在文件中,然后再重新列出,因为我希望能够实时接收它。)
使用ProcessStartInfo.RedirectStandardOutput属性可以轻松实现此目的。完整示例包含在链接的MSDN文档中;唯一的注意事项是您可能还需要重定向标准错误流以查看应用程序的所有输出。
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();
Console.Write
即可。 - tm1这是比@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");
}
使用ProcessStartInfo.RedirectStandardOutput在创建控制台进程时重定向输出。
然后可以使用Process.StandardOutput读取程序输出。
第二个链接提供了一个如何操作的示例代码。
ConsoleAppLauncher 是一个专门回答这个问题的开源库。它捕获控制台生成的所有输出,并提供简单的界面来启动和关闭控制台应用程序。
每次控制台向标准/错误输出写入新行时,都会触发 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();
}
我制作了一个响应式版本,它接受stdOut和StdErr的回调函数。
onStdOut
和 onStdErr
在数据到达时(进程退出之前)异步调用。
public static Int32 RunProcess(String path,
String args,
Action<String> onStdOut = null,
Action<String> onStdErr = null)
{
var readStdOut = onStdOut != null;
var readStdErr = onStdErr != null;
var process = new Process
{
StartInfo =
{
FileName = path,
Arguments = args,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = readStdOut,
RedirectStandardError = readStdErr,
}
};
process.Start();
if (readStdOut) Task.Run(() => ReadStream(process.StandardOutput, onStdOut));
if (readStdErr) Task.Run(() => ReadStream(process.StandardError, onStdErr));
process.WaitForExit();
return process.ExitCode;
}
private static void ReadStream(TextReader textReader, Action<String> callback)
{
while (true)
{
var line = textReader.ReadLine();
if (line == null)
break;
callback(line);
}
}
以下代码将运行带有参数args
的executable
并将输出打印到控制台:
RunProcess(
executable,
args,
s => { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(s); },
s => { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(s); }
);
来自PythonTR - Python Programcı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
添加了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;
}
}
}
StandardOutput.ReadToEnd()
时,它不会返回到下一个语句,直到应用程序结束。因此,您在WaitForExit(timeoutMilliseconds)中设置的超时时间不起作用!(您的代码将挂起!) - S.Serpooshan