如何合并providers.exec的标准输出与错误输出?
解决
providers.exec获取合并输出的方案 由于providers.exec为兼容配置缓存,禁止直接配置标准输出/错误输出流,可通过以下两种方式获取包含标准输出与错误输出的完整控制台内容:
方法一:命令级重定向(保持输出顺序)
让执行的命令自身将错误输出重定向到标准输出,不同系统语法略有差异:
val execResult = providers.exec { // *nix/macOS环境 commandLine("sh", "-c", args.joinToString(" ") + " 2>&1") // Windows环境替换为:commandLine("cmd", "/c", args.joinToString(" ") + " 2>&1") isIgnoreExitValue = true }.get() return CommandExecutionResult( exitCode = execResult.exitValue, consoleOutput = execResult.output )
方法二:手动合并输出(顺序可能有差异)
分别获取标准输出和错误输出后手动拼接,缺点是输出顺序可能和实际执行时的交替输出不一致:
val execResult = providers.exec { commandLine(*args) isIgnoreExitValue = true }.get() val combinedOutput = execResult.output + execResult.errorOutput return CommandExecutionResult( exitCode = execResult.exitValue, consoleOutput = combinedOutput )
内容的提问来源于stack exchange,提问作者Kirill
相关产品推荐
相关产品推荐

