You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在SimpleExec中如何将Command.Run()的返回值存入变量?

在.NET C#中使用SimpleExec捕获命令执行结果

如果需要把SimpleExec执行命令的结果赋值给变量,别用Run方法,改用Read或ReadAsync方法——这两个方法专门用来捕获命令的标准输出内容:

基础用法(同步/异步)

using SimpleExec;

// 同步捕获git版本信息
string gitVersion = Command.Read("git", "version");

// 异步捕获(推荐在异步场景使用)
string gitVersionAsync = await Command.ReadAsync("git", "version");

捕获标准错误输出与自定义选项

如果需要同时获取标准错误输出,或者调整命令执行的行为,可以通过配置选项实现:

var executionResult = await Command.ReadAsync("git", "version", options =>
{
    options.CaptureError = true; // 开启标准错误捕获
    // 其他可选配置:比如设置工作目录、环境变量等
});

// 访问输出内容
string stdOut = executionResult.StandardOutput;
string stdErr = executionResult.StandardError;
int exitCode = executionResult.ExitCode;

自定义错误处理

SimpleExec默认会在命令返回非0退出码时抛出NonZeroExitCodeException。如果想手动处理错误,可关闭自动抛出:

var result = await Command.ReadAsync("git", "invalid-subcommand", options =>
{
    options.ThrowOnError = false;
});

if (result.ExitCode != 0)
{
    // 这里写命令执行失败后的处理逻辑
}

内容的提问来源于stack exchange,提问作者Artie Leech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 00:22:03