亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

exec,Cmd.Run() 沒有正確運行帶參數的命令

exec,Cmd.Run() 沒有正確運行帶參數的命令

Go
一只甜甜圈 2022-07-18 16:42:36
go version go1.15.6 windows/amd64 dev os Windows [版本 10.0.19041.630]我有一個 Go 應用程序,我在其中使用 exec.Cmd.Run() 運行 AWS CLI。我構建了 Cmd 類并填充了參數。在運行 Cmd 之前,我使用 .String() 方法查看要運行的命令。如果我采用此值,將其復制到 shell,則命令執行時不會對提供給我的輸出進行任何修改,也不會報告任何問題。但是,當我運行該命令時,它無法返回錯誤。當我調試腳本時,它失敗了,因為它說 AWS CLI 說參數不正確。問題:是否可以看到正在運行的內容的 100% 原始表示?它與 .String() 的返回值不匹配有沒有更好的方法來調用我缺少的操作系統級別命令?真實例子:cmd := &exec.Cmd{    Path:   awsPath,    Args:   args,    Stdout: &stdout,    Stderr: &stderr,}fmt.Printf("Command: %s\n", cmd.String())// c:\PROGRA~1\Amazon\AWSCLIV2\aws.exe --profile testprofile --region us-east-1 --output json ec2 describe-network-interfaces --filters Name=group-id,Values=sg-abc123// Running above works 100% of the time if ran from a shell windowerr := cmd.Run()// always errors out saying the format is incorrectGoPlayground 復制問題 https://play.golang.org/p/mvV9VG8F0oz
查看完整描述

2 回答

?
犯罪嫌疑人X

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 字符等。并對每個參數使用相同的技術。


查看完整回答
反對 回復 2022-07-18
?
蝴蝶不菲

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"

完畢。


查看完整回答
反對 回復 2022-07-18
  • 2 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號