使用 C# 捕获进程输出
使用 C# 捕获进程输出
Intro
很多时候我们可能会需要执行一段命令获取一个输出,遇到的比较典型的就是之前我们需要用 FFMpeg 实现视频的编码压缩水印等一系列操作,当时使用的是 FFMpegCore 这个类库,这个类库的实现原理是启动另外一个进程,启动 ffmpeg 并传递相应的处理参数,并根据进程输出获取处理进度
为了方便使用,实现了两个帮助类来方便的获取进程的输出,分别是 ProcessExecutor 和 CommandRunner,前者更为灵活,可以通过事件添加自己的额外事件订阅处理,后者为简化版,主要是只获取输出的场景,两者的实现原理大体是一样的,启动一个 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
使用 C# 捕获进程输出的更多相关文章
- [linux] C语言Linux系统编程-捕获进程信号
typedef void( *sighandler_t)(int); 1.用typedef给类型起一个别名. 2.为函数指针类型定义别名, 3.函数指针(指向函数的指针) sighandler_t s ...
- sql存储过程异常捕获并输出例子还有不输出过程里面判断异常 例子
编程的异常处理很重要,当然Sql语句中存储过程的异常处理也很重要,明确的异常提示能够快速的找到问题的根源,节省很多时间. 下面,我就以一个插入数据为例来说明Sql Server中的存储过程怎么捕获异常 ...
- shell无法捕获程序输出的问题
dir_name=`echo ~gtp` 获取的用户目录为/ dir_name=`echo ~gtp 2>&1` 这样就可以获取到了 参考网址:https://blog.csdn.net ...
- 一条命令,根据进程名判断有进程输出up,无进程无输出
这个研究了好一会, 由于开发需要,提供的命令. shell命令,可以按照分号分割,也可以按照换行符分割.如果想一行写入多个命令,可以通过“';”分割. a=`ps -ef | grep nginx | ...
- DirectX屏幕捕获和输出视频
#include <Windows.h> #include <mfapi.h> #include <mfidl.h> #include <Mfreadwrit ...
- python中如何用sys.excepthook来对全局异常进行捕获、显示及输出到error日志中
使用sys.excepthook函数进行全局异常的获取. 1. 使用MessageDialog实现异常显示: 2. 使用logger把捕获的异常信息输出到日志中: 步骤:定义异常处理函数, 并使用该函 ...
- Java示例:如何执行进程并读取输出
下面是一个例子,演示如何执行一个进程(类似于在命令行下键入命令),读取进程执行的输出,并根据进程的返回值判断是否执行成功.一般来说,进程返回 0 表示执行成功,其他值表示失败. import java ...
- stm32f103_高级定时器——输入捕获/输出比较中断+pwm=spwm生成
****************************首选我们了解一下它们的功能吧********************************************************** ...
- 内核创建的用户进程printf不能输出一问的研究
转:http://www.360doc.com/content/09/0315/10/26398_2812414.shtml 一:前言上个星期同事无意间说起,在用核中创建的用户空间进程中,使用prin ...
随机推荐
- 2019 HL SC day1
今天讲的是图论大体上分为:有向图的强连通分量,有向图的完全图:竞赛图,无向图的的割点,割边,点双联通分量,变双联通分量以及圆方树 2-sat问题 支配树等等. 大体上都知道是些什么东西 但是仍需要写一 ...
- Maven知识记录(一)初识Maven私服
Maven知识记录(一)初识Maven私服 什么是maven私服 私服即私有的仓库.maven把存放文件的地方叫做仓库,我们可以理解成我门家中的储物间.而maven把存放文件的具体位置叫做坐标.我们项 ...
- [COCOS2DX-LUA]0-006.cocos2dx中关于拖动屏幕物件,同时点击home键,返回后页面变黑的问题。
基本信息介绍: 引擎框架: Quick-Cocos2dx-Community-3.6 测试机型: 魅族MX5 问题简介: 有拖动效果的物件,在拖动的工程中,手指不放,同时点击home键退到后台. 再返 ...
- 使用Luhn算法实现信用卡号验证
问题描述: 2:信用卡号的验证 [信用卡号的验证] 当你输入信用卡号码的时候,有没有担心输错了而造成损失呢?其实可以不必这么 担心,因为并不是一个随便的信用卡号码都是合法的,它必须通过 Luhn 算法 ...
- java_数组的定义与操作
数组定义和访问 数组概念 数组概念: 数组就是存储多个数据的容器,数组的长度固定,多个数据的数据类型要一致. 数组的定义 方式一 数组存储的数据类型[] 数组名字 = new 数组存储的数据类型[长度 ...
- 怎么用 Solon 开发基于 undertow jsp tld 的项目?
Solon 开发 jsp 还是简单的,可以有 jetty 启动器 或者 undertow 启动器.此文用 undertow + jsp + tld 这个套路搞一把: 一. 开始Meven配置走起 用s ...
- springboot多环境部署(profile多环境支持)
springboot多环境部署(profile多环境支持) 背景 项目开发过程中会有开发环境(dev),测试环境(test)和生产环境(prod),不同的环境需要配置不同的配置,profile提供 ...
- C#LeetCode刷题之#671-二叉树中第二小的节点(Second Minimum Node In a Binary Tree)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4100 访问. 给定一个非空特殊的二叉树,每个节点都是正数,并且每 ...
- 思维导图概览SpringCloud
@ 目录 1.什么是微服务 1.1.架构演进 1.2.微服务架构 1.3.微服务解决方案 2.SpringCloud概览 2.1.什么是SpringCloud 2.1.SpringCloud主要组件 ...
- js截取URL网址参数
将本页代码复制粘贴到html页面,打开即可. <!DOCTYPE html> <html lang="en"> <head> <meta ...