如何使用C# 捕获进程输出
Intro
很多时候我们可能会需要执行一段命令获取一个输出,遇到的比较典型的就是之前我们需要用FFMpeg实现视频的编码压缩水印等一系列操作,当时使用的是FFMpegCore这个类库,这个类库的实现原理是启动另外一个进程,启动ffmpeg并传递相应的处理参数,并根据进程输出获取处理进度
为了方便使用,实现了两个帮助类来方便的获取进程的输出,分别是ProcessExecutor和CommandRunner,前者更为灵活,可以通过事件添加自己的额外事件订阅处理,后者为简化版,主要是只获取输出的场景,两者的实现原理大体是一样的,启动一个Process,并监听其输出事件获取输出
ProcessExecutor
使用示例,这个示例是获取保存nuget包的路径的一个示例:
usingvarexecutor=newProcessExecutor("dotnet","nugetlocalsglobal-packages-l"); varfolder=string.Empty; executor.OnOutputDataReceived+=(sender,str)=> { if(strisnull) return; Console.WriteLine(str); if(str.StartsWith("global-packages:")) { folder=str.Substring("global-packages:".Length).Trim(); } }; executor.Execute(); Console.WriteLine(folder);
ProcessExecutor实现代码如下:
publicclassProcessExecutor:IDisposable { publiceventEventHandlerOnExited; publiceventEventHandler OnOutputDataReceived; publiceventEventHandler OnErrorDataReceived; protectedreadonlyProcess_process; protectedbool_started; publicProcessExecutor(stringexePath):this(newProcessStartInfo(exePath)) { } publicProcessExecutor(stringexePath,stringarguments):this(newProcessStartInfo(exePath,arguments)) { } publicProcessExecutor(ProcessStartInfostartInfo) { _process=newProcess() { StartInfo=startInfo, EnableRaisingEvents=true, }; _process.StartInfo.UseShellExecute=false; _process.StartInfo.CreateNoWindow=true; _process.StartInfo.RedirectStandardOutput=true; _process.StartInfo.RedirectStandardInput=true; _process.StartInfo.RedirectStandardError=true; } protectedvirtualvoidInitializeEvents() { _process.OutputDataReceived+=(sender,args)=> { if(args.Data!=null) { OnOutputDataReceived?.Invoke(sender,args.Data); } }; _process.ErrorDataReceived+=(sender,args)=> { if(args.Data!=null) { OnErrorDataReceived?.Invoke(sender,args.Data); } }; _process.Exited+=(sender,args)=> { if(senderisProcessprocess) { OnExited?.Invoke(sender,process.ExitCode); } else { OnExited?.Invoke(sender,_process.ExitCode); } }; } protectedvirtualvoidStart() { if(_started) { return; } _started=true; _process.Start(); _process.BeginOutputReadLine(); _process.BeginErrorReadLine(); _process.WaitForExit(); } publicasyncvirtualTaskSendInput(stringinput) { try { await_process.StandardInput.WriteAsync(input!); } catch(Exceptione) { OnErrorDataReceived?.Invoke(_process,e.ToString()); } } publicvirtualintExecute() { InitializeEvents(); Start(); return_process.ExitCode; } publicvirtualasyncTask ExecuteAsync() { InitializeEvents(); returnawaitTask.Run(()=> { Start(); return_process.ExitCode; }).ConfigureAwait(false); } publicvirtualvoidDispose() { _process.Dispose(); OnExited=null; OnOutputDataReceived=null; OnErrorDataReceived=null; } }
CommandExecutor
上面的这种方式比较灵活但有些繁琐,于是有了下面这个版本
使用示例:
[Fact] publicvoidHostNameTest() { if(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } varresult=CommandRunner.ExecuteAndCapture("hostname"); varhostName=Dns.GetHostName(); Assert.Equal(hostName,result.StandardOut.TrimEnd()); Assert.Equal(0,result.ExitCode); }
实现源码:
publicstaticclassCommandRunner { publicstaticintExecute(stringcommandPath,stringarguments=null,stringworkingDirectory=null) { usingvarprocess=newProcess() { StartInfo=newProcessStartInfo(commandPath,arguments??string.Empty) { UseShellExecute=false, CreateNoWindow=true, WorkingDirectory=workingDirectory??Environment.CurrentDirectory } }; process.Start(); process.WaitForExit(); returnprocess.ExitCode; } publicstaticCommandResultExecuteAndCapture(stringcommandPath,stringarguments=null,stringworkingDirectory=null) { usingvarprocess=newProcess() { StartInfo=newProcessStartInfo(commandPath,arguments??string.Empty) { UseShellExecute=false, CreateNoWindow=true, RedirectStandardOutput=true, RedirectStandardError=true, WorkingDirectory=workingDirectory??Environment.CurrentDirectory } }; process.Start(); varstandardOut=process.StandardOutput.ReadToEnd(); varstandardError=process.StandardError.ReadToEnd(); process.WaitForExit(); returnnewCommandResult(process.ExitCode,standardOut,standardError); } } publicsealedclassCommandResult { publicCommandResult(intexitCode,stringstandardOut,stringstandardError) { ExitCode=exitCode; StandardOut=standardOut; StandardError=standardError; } publicstringStandardOut{get;} publicstringStandardError{get;} publicintExitCode{get;} }
More
如果只要执行命令获取是否执行成功则使用CommandRunner.Execute即可,只获取输出和是否成功可以用CommandRunner.ExecuteAndCapture方法,如果想要进一步的添加事件订阅则使用ProcessExecutor
Reference
https://github.com/rosenbjerg/FFMpegCore
https://github.com/WeihanLi/WeihanLi.Common/blob/dev/src/WeihanLi.Common/Helpers/ProcessExecutor.cs
https://github.com/WeihanLi/WeihanLi.Common/blob/dev/test/WeihanLi.Common.Test/HelpersTest/ProcessExecutorTest.cs
https://github.com/WeihanLi/WeihanLi.Common/blob/dev/test/WeihanLi.Common.Test/HelpersTest/CommandRunnerTest.cs
以上就是如何使用C#捕获进程输出的详细内容,更多关于C#捕获进程输出的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。