2 回答

TA貢獻2080條經驗 獲得超4個贊
從cmd.String來源:
// String returns a human-readable description of c.
// It is intended only for debugging.
// In particular, it is not suitable for use as input to a shell.
// The output of String may vary across Go releases.
您看到的是相反的情況,但問題是相同的:目測打印的命令字符串不會顯示確切的可執行路徑(是否存在流氓空格或不可打印的字符?),與參數(流氓字符?)相同。
用于fmt.Printf("cmd : %q\n", cmd.Path)顯示任何隱藏的 unicode 字符等。并對每個參數使用相同的技術。

TA貢獻1810條經驗 獲得超4個贊
我找到了您遇到的問題的根本原因:os/exec
// Path is the path of the command to run.
//
// This is the only field that must be set to a non-zero
// value. If Path is relative, it is evaluated relative
// to Dir.
Path string
// Args holds command line arguments, including the command as **Args[0]**.
// If the Args field is empty or nil, Run uses {Path}.
//
// In typical use, both Path and Args are set by calling Command.
Args []string
因此,如果您已聲明Cmd.Path := "/usr/local/bin/aws",則必須像這樣聲明Cmd. Args:Args: []string{"", "s3", "help"},因為Args包含上述文檔鏈接中的命令Args[0]。最后,我認為您可以簡單有效地執行這樣的命令:
package main
import (
"bytes"
"fmt"
"os/exec"
)
func main() {
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
name := "/usr/local/bin/aws"
arg := []string{"s3", "help"}
cmd := exec.Command(name, arg...)
cmd.Stderr = stderr
cmd.Stdout = stdout
fmt.Printf("Command: %q\n", cmd.String())
err := cmd.Run()
if err != nil {
fmt.Println("Error: ", stderr.String())
}
fmt.Println("Output: ", stdout.String())
}
=========
$ go run main.go
Command: "/usr/local/bin/aws s3 help"
完畢。
- 2 回答
- 0 關注
- 151 瀏覽
添加回答
舉報