使用 C# 捕获进程输出

在 .net 中捕获进程输出

Intro

很多时候我们可能会需要执行一段命令获取一个输出,遇到的比较典型的就是之前我们需要用 FFMpeg 实现视频的编码压缩水印等一系列操作,当时使用的是 FFMpegCore 这个类库,这个类库的实现原理是启动另外一个进程,启动 ffmpeg 并传递相应的处理参数,并根据进程输出获取处理进度,处理结果等信息

为了方便使用,实现了两个帮助类来方便的获取进程的输出,分别是 ProcessExecutorCommandRunner,前者更为灵活,可以通过事件添加自己的额外事件订阅处理,后者为简化版,主要是只获取输出的场景,两者的实现原理大体是一样的,启动一个 Process,并监听其输出事件获取输出

ProcessExecutor

使用示例,这个示例是获取保存 nuget 包的路径的一个示例:

using var executor = new ProcessExecutor("dotnet", "nuget locals global-packages -l");
var folder = string.Empty;
executor.OnOutputDataReceived += (sender, str) =>
{if(str is null)return;Console.WriteLine(str);if(str.StartsWith("global-packages:")){folder = str.Substring("global-packages:".Length).Trim();                    }
};
executor.Execute();Console.WriteLine(folder);

ProcessExecutor 实现代码如下:

public class ProcessExecutor : IDisposable
{public event EventHandler<int> OnExited;public event EventHandler<string> OnOutputDataReceived;public event EventHandler<string> OnErrorDataReceived;protected readonly Process _process;protected bool _started;public ProcessExecutor(string exePath) : this(new ProcessStartInfo(exePath)){}public ProcessExecutor(string exePath, string arguments) : this(new ProcessStartInfo(exePath, arguments)){}public ProcessExecutor(ProcessStartInfo startInfo){_process = new Process(){StartInfo = startInfo,EnableRaisingEvents = true,};_process.StartInfo.UseShellExecute = false;_process.StartInfo.CreateNoWindow = true;_process.StartInfo.RedirectStandardOutput = true;_process.StartInfo.RedirectStandardInput = true;_process.StartInfo.RedirectStandardError = true;}protected virtual void InitializeEvents(){_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 (sender is Process process){OnExited?.Invoke(sender, process.ExitCode);}else{OnExited?.Invoke(sender, _process.ExitCode);}};}protected virtual void Start(){if (_started){return;}_started = true;_process.Start();_process.BeginOutputReadLine();_process.BeginErrorReadLine();_process.WaitForExit();}public async virtual Task SendInput(string input){try{await _process.StandardInput.WriteAsync(input!);}catch (Exception e){OnErrorDataReceived?.Invoke(_process, e.ToString());}}public virtual int Execute(){InitializeEvents();Start();return _process.ExitCode;}public virtual async Task<int> ExecuteAsync(){InitializeEvents();return await Task.Run(() =>{Start();return _process.ExitCode;}).ConfigureAwait(false);}public virtual void Dispose(){_process.Dispose();OnExited = null;OnOutputDataReceived = null;OnErrorDataReceived = null;}
}

CommandExecutor

上面的这种方式比较灵活但有些繁琐,于是有了下面这个版本

使用示例:

[Fact]
public void HostNameTest()
{if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)){return;}var result = CommandRunner.ExecuteAndCapture("hostname");var hostName = Dns.GetHostName();Assert.Equal(hostName, result.StandardOut.TrimEnd());Assert.Equal(0, result.ExitCode);
}

实现源码:

public static class CommandRunner
{public static int Execute(string commandPath, string arguments = null, string workingDirectory = null){using var process = new Process(){StartInfo = new ProcessStartInfo(commandPath, arguments ?? string.Empty){UseShellExecute = false,CreateNoWindow = true,WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory}};process.Start();process.WaitForExit();return process.ExitCode;}public static CommandResult ExecuteAndCapture(string commandPath, string arguments = null, string workingDirectory = null){using var process = new Process(){StartInfo = new ProcessStartInfo(commandPath, arguments ?? string.Empty){UseShellExecute = false,CreateNoWindow = true,RedirectStandardOutput = true,RedirectStandardError = true,WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory}};process.Start();var standardOut = process.StandardOutput.ReadToEnd();var standardError = process.StandardError.ReadToEnd();process.WaitForExit();return new CommandResult(process.ExitCode, standardOut, standardError);}
}public sealed class CommandResult
{public CommandResult(int exitCode, string standardOut, string standardError){ExitCode = exitCode;StandardOut = standardOut;StandardError = standardError;}public string StandardOut { get; }public string StandardError { get; }public int ExitCode { 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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/307991.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode:203. 移除链表元素(两种方法)

一:题目 二:上码 1:方法一&#xff1a;(虚拟一个首结点) class Solution { public:ListNode* removeElements(ListNode* head, int val) {//1.虚拟一个头结点 这样就不用单独处理了ListNode * virtuals new ListNode(0);//给其开辟个空间并且赋初值virtuals->next head…

面试中的网红虚拟DOM,你知多少呢?深入解读diff算法

深入浅出虚拟DOM和diff算法一、虚拟DOM&#xff08;Vitual DOM&#xff09;1、虚拟DOM&#xff08;Vitual DOM&#xff09;和diff的关系2、真实DOM的渲染过程3、虚拟DOM是什么&#xff1f;4、解决方案 - vdom&#xff08;1&#xff09;问题引出&#xff08;2&#xff09;vdom如…

Blazor带我重玩前端(六)

本文主要讨论Blazor事件内容&#xff0c;由于blazor事件部分很多&#xff0c;所以会分成上下两篇&#xff0c;本文为第二篇。双向绑定概述如图所示当点击单项绑定的时候&#xff0c;MyOnewayComponent里的属性值会发生变化&#xff0c;这种变化是单项的&#xff0c;仅仅只是本地…

leetcode707:设计链表(增删差)

一:题目 二:上码 class MyLinkedList { public://定义链表节点结构体struct LinkedNode {int val;LinkedNode* next;LinkedNode(int val):val(val), next(nullptr){}};// 初始化链表MyLinkedList() {node new LinkedNode(0); // 这里定义的头结点 是一个虚拟头结点&#xff0…

深入探究.Net Core Configuration读取配置的优先级

前言在之前的文章.Net Core Configuration源码探究一文中我们曾解读过Configuration的工作原理&#xff0c;也.Net Core Configuration Etcd数据源一文中探讨过为Configuration自定义数据源需要哪些操作。由于Configuration配置系统也是.Net Core的核心&#xff0c;其中也包含了…

TypeScript,从0到入门带你进入类型的世界

从0到入门进入TS的世界一、什么是TypeScript&#xff1f;1、编程语言的类型2、TypeScript究竟是什么&#xff1f;二、为什么要学习TypeScript&#xff1f;1、程序更容易理解2、效率更高3、更少的错误4、非常好的包容性5、一点小缺点三、typescript入门1、如何安装TypeScript2、…

编写第一个 .NET 微服务

介绍本文的目的是&#xff1a;通过创建一个返回列表的简单服务&#xff0c;并在 Docker 容器中运行该服务&#xff0c;让您熟悉使用 .NET 创建微服务的构建过程。安装 .NET SDK要开始构建 .NET 应用程序&#xff0c;首先下载并安装 .NET Core SDK&#xff08;软件开发工具包&am…

模板编译template的背后,究竟发生了什么事?带你了解template的纸短情长

解析模板编译template的背后发生了什么一、&#x1f4d1;初识模板编译1、vue组件中使用render代替template2、模板编译总结二、✏️感受模板编译的美1、with语法&#xff08;1&#xff09;例子展示&#x1f330;&#xff08;2&#xff09;知识点归纳三、&#x1f4c8;编译模板1…

leetcode24. 两两交换链表中的节点(思路+解析)

一:题目 二:思路 思路: 1.分析题意 这是相邻结点进行交换 如果是4个结点 那么1和2交换 3和4交换 如果是3个结点 那么就1和2进行交换 3不动 2.这里我们定义一个虚拟头节点方便操作&#xff0c;我们只需三步实现结点的交换 <1>:让虚拟结点指向第二个结点(进行交换的结点我…

把Autofac玩的和java Spring一样6

大家好&#xff0c;今天来介绍我开源的一个autofac.Annotation项目 源码&#xff1a;https://github.com/yuzd/Autofac.Annotation本项目是autofa的一个扩展组件&#xff0c;autofac是一个老牌的DI容器框架 &#xff0c;支持netframework和netcoreAnnotdation是注解的意思&…

『软件测试5』测开岗只要求会黑白盒测试?NO!还要学会性能测试!

浅谈软件测试中的性能测试一、&#x1f92a;性能测试概念1、为什么要有性能测试&#xff1f;2、性能测试是什么&#xff1f;3、性能测试的目的二、&#x1f910;性能测试指标1、响应时间2、吞吐量3、并发用户数4、TPS(Transaction Per Second)5、点击率6、资源利用率三、&#…

CLR的简单理解

CLR加载程序生成进程&#xff0c;一个进程中可以存在多个线程&#xff0c;当创建一个线程时&#xff0c;会分配1Mb的空间&#xff0c;也就是线程的栈空间&#xff0c;对应jvm的虚拟机堆栈&#xff0c;是线程执行过程中用到的工作内存。这片内存用于方法传递实参&#xff0c;并存…

『软件测试6』bug一两是小事,但安全漏洞是大事!

详解软件测试中的安全测试一、&#x1f4bf;安全测试概念1、安全测试概述2、安全测试与软件生命周期的关系3、常规测试与安全测试的不同&#xff08;1&#xff09;测试目标不同&#xff08;2&#xff09;假设条件不同&#xff08;3&#xff09;思考域不同&#xff08;4&#xf…

我们真的需要JWT吗?

JWT&#xff08;JSON Web Token&#xff09;是目前最流行的认证方案之一。博客园、各种技术公众号隔三差五就会推一篇JWT相关的文章&#xff0c;真的多如牛毛。但我对JWT有点困惑&#xff0c;今天写出来跟大家探讨探讨&#xff0c;不要喷哈。JWT原理本文默认读者已经对JWT有所了…

leetcode面试题 02.07. 链表相交

一:题目 二:思路 1.这道题我们是需要找到一个结点&#xff0c;并且从这个结点往后的结点都相等 2.我们需要将两个链表 右对齐 3.然后将长链表的指针移动到和短链表头结点相同的位置 4.接下来就是比较指针&#xff0c;当一个指针相同也就意味着往后的结点的数值也相等 三:上码…

详解队列在前端的应用,深剖JS中的事件循环Eventloop,再了解微任务和宏任务

队列在前端中的应用一、队列是什么二、应用场景三、前端与队列&#xff1a;事件循环与任务队列1、event loop2、JS如何执行3、event loop过程4、 DOM 事件和 event loop5、event loop 总结四、宏任务和微任务1、引例2、宏任务和微任务&#xff08;1&#xff09;常用的宏任务和微…

终于弄明白了 Singleton,Transient,Scoped 的作用域是如何实现的

一&#xff1a;背景1. 讲故事前几天有位朋友让我有时间分析一下 aspnetcore 中为什么向 ServiceCollection 中注入的 Class 可以做到 Singleton&#xff0c;Transient&#xff0c;Scoped&#xff0c;挺有意思&#xff0c;这篇就来聊一聊这一话题&#xff0c;自从 core 中有了 S…

leetcode142. 环形链表 II(暴力+双链表)

一:题目 二:思路 1.双指针 快慢指针(快指针一次一个结点&#xff0c;慢指针一次两个结点) 2.如果有环的话&#xff0c;那么快慢指针肯定会相遇 3.那么相遇的地点一定在环中 因为如果没有环的话慢指针是永远追不到快指针的 4.接下来就是判断出口在那里&#xff0c;我们定义一个…

动态 Restful API 生成

介绍通常在DDD开发架构中&#xff0c;我们写完服务层需要在控制器中写API&#xff0c;今天介绍一个组件 Plus.AutoApi 可以用它来动态生成 Restful 风格的 WebApi&#xff0c;不用写 Controller。快速使用在你的应用服务层中添加组件Install-Package Plus.AutoApi在 Startup 中…

卷死了!再不学vue3就没有人要你了!速来围观vue3新特性

一文全面了解vue3新特性一、&#x1f636;vue3比vue2有什么优势&#xff1f;二、&#x1f9d0;Vue3升级了哪些重要的功能1、createApp2、emits(父子组件间的通信)&#xff08;1&#xff09;通信方式&#xff08;2&#xff09;举个例子&#x1f330;3、多事件处理4、Fragment5、…