故事是这样的:我有一个名为coletorbeat的程序,需要运行一个大参数。此参数基于一些参数。我构建了另一个名为bootstrapper的程序,该程序采用这些参数,构建coletorbeat所需的long参数,然后应运行coletorbeat,将long参数作为输入。
我尝试了多种方式,使用转义引号,反引号等。但是由于某种原因,该程序被调用,好像根本没有传递任何参数。我什至没有错误消息。
我将在下面发布代码,非常感谢您的帮助。
诸如coletorbeat.ip =%v之类的字段应出现在命令行中的引号或反引号内,并以-E开头。

package main

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

func main() {
    if len(os.Args) < 8 {
        fmt.Printf("%v arguments were given. 8 needed to work", len(os.Args))
        return
    }
    // Parâmetros devem ser passados na ordem: ip, porta, data_inicio, data_fim, tipo_equipamento, versao, nivel, instituicao
    //There can`t be empty spaces on any of the strings inside the Args. We gotta do some prevention in case it happens here.

    flag := "-E"
    Arg1 := fmt.Sprintf("`coletorbeat.ip=%v`", os.Args[1])
    Arg2 := fmt.Sprintf("`coletorbeat.porta=%v`", os.Args[2])
    Arg3 := fmt.Sprintf("`coletorbeat.dataInicio=%v`", os.Args[3])
    Arg4 := fmt.Sprintf("`coletorbeat.dataFim=%v`", os.Args[4])
    Arg5 := fmt.Sprintf("`coletorbeat.tipoEquipamento=%v`", os.Args[5])
    Arg6 := fmt.Sprintf("`coletorbeat.versao=%v`", os.Args[6])
    Arg7 := fmt.Sprintf("`coletorbeat.nivel=%v`", os.Args[7])
    Arg8 := fmt.Sprintf("`coletorbeat.instituicao=%v`", os.Args[8])
    Arg9 := fmt.Sprintf("`output.elasticsearch.index=collectorbeat-%v-%v-%v-%v`", os.Args[8], os.Args[5], time.Now().Format("20060201"), os.Args[1])

    commandToExecute := &exec.Cmd{
        Path: "coletorbeat",
        Args: []string{"./", flag, Arg1, flag, Arg2, flag, Arg3, flag, Arg4, flag, Arg5, flag, Arg6, flag, Arg7, flag, Arg8, flag, Arg9},
        Stdout: os.Stdout,
        Stderr: os.Stdout,
    }
    fmt.Println(commandToExecute.Args)
    fmt.Println("Copy the code")
    if err := commandToExecute.Run(); err != nil {
        fmt.Println("error caught on Bootstrapper")
        fmt.Println("Error: ", err)
    }
}

最佳答案

奇怪的是,以下解决方案解决了该问题:

func main() {
    if len(os.Args) < 8 {
        fmt.Printf("%v arguments were given. 8 needed to work", len(os.Args))
        return
    }

    cmd := exec.Command("full/canonical/executable/file/path", "-E", fmt.Sprintf("\"coletorbeat.ip=%v\"", os.Args[1]), "-E", fmt.Sprintf("\"coletorbeat.porta=%v\"", os.Args[2]), "-E", fmt.Sprintf("\"coletorbeat.dataInicio=%v\"", os.Args[3]), "-E", fmt.Sprintf("\"coletorbeat.dataFim=%v\"", os.Args[4]), "-E", fmt.Sprintf("\"coletorbeat.tipoEquipamento=%v\"", os.Args[5]), "-E", fmt.Sprintf("\"coletorbeat.versao=%v\"", os.Args[6]), "-E", fmt.Sprintf("\"coletorbeat.nivel=%v\"", os.Args[7]), "-E", fmt.Sprintf("\"coletorbeat.instituicao=%v\"", os.Args[8]), "-E", fmt.Sprintf("\"output.elasticsearch.index=collectorbeat-%v-%v-%v-%v\"", os.Args[8], os.Args[5], time.Now().Format("20060201"), os.Args[1]))

    fmt.Println(cmd.Args)

    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Run()
    fmt.Println(fmt.Sprint(err) + ": " + out.String())
}

10-02 10:44