gpt4 book ai didi

go - Nginx version 命令不返回版本也不返回错误

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:22 25 4
gpt4 key购买 nike

我正在尝试使用 Go 检查我的计算机上安装了哪个版本的 Nginx。

这是我的代码片段:

package main

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

func runCommand(command string, arg ...string) (string, error) {
cmd := exec.Command(command, arg...)
cmdOutput := &bytes.Buffer{}
errOutput := &bytes.Buffer{}
cmd.Stdout = cmdOutput
cmd.Stderr = errOutput
err := cmd.Run()
if err != nil {
return "", errors.New(string(errOutput.Bytes()))
}
fmt.Println("Command succeeded")
return string(cmdOutput.Bytes()), nil
}

func getVersion(command string, arg ...string) {
path, err := exec.LookPath(command)
if err != nil {
fmt.Println("No path for " + command + " found")
return
}
fmt.Println("Path for " + command + " is " + path)

result, err := runCommand(path, arg...)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(command + " version is: " + result)
}

func main() {
getVersion("go", "version") // works
getVersion("nginx", "-v") // does not work
getVersion("firefox", "-v") // works
}

对于 Go 和 Firefox,它工作得很好,但是对于 Nginx,它既不返回版本也不返回错误。它似乎返回一个空字符串...

查看权限:Firefox 文件是 root:root 拥有的 sh 文件的符号链接(symbolic link),权限为 755。Nginx 文件由 root:root 拥有,权限也是 755。

当然,运行命令 nginx -v 是可行的。

最佳答案

您期待标准输出的输出。它正在打印到 stderr。试试 cmd.CombinedOutput()

关于go - Nginx version 命令不返回版本也不返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57731024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com