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

Go新手使用exec.Command执行GPG校验时输出为空问题排查

问题排查:Go调用gpg --verify时out为空的原因

嘿,这个问题我之前帮朋友踩过坑!其实核心原因是gpg的输出流向和你想的不一样。

当你在终端手动执行gpg --verify xyz.json.sig xyz.json时,终端会同时显示标准输出(stdout)和标准错误(stderr)的内容,但Go的exec.Command().Output()方法只会捕获stdout的输出。而gpg默认会把校验成功的提示信息(比如“Good signature from ...”这类内容)输出到stderr,不是stdout,所以你的out变量自然是空的——但这时候校验其实是成功的,err也不会返回错误。

解决方案

最简单的修复方式是用CombinedOutput()代替Output(),这个方法会把stdout和stderr的内容合并返回,这样你就能拿到完整的校验输出了:

package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    out, err := exec.Command("gpg", "--verify", "xyz.json.sig", "xyz.json").CombinedOutput()
    if err != nil {
        fmt.Printf("校验失败:%v\n", err)
        fmt.Printf("详细错误信息:%s\n", out)
        os.Exit(1)
    }
    fmt.Printf("校验成功,输出内容:\n%s\n", out)
}

如果你需要分别处理stdout和stderr(比如区分正常信息和错误信息),也可以用StdoutPipe()和StderrPipe()手动捕获两个流,但对于你的简单校验场景,CombinedOutput()已经完全够用啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:07:28