小编ash*_*oke的帖子

如何在Golang中使用未知参数执行系统命令

我有一堆系统命令,它们与将新内容附加到文件有点类似.我编写了一个简单的脚本来执行系统命令,如果有单个单词如'ls','date'等,它会很好用.但是如果命令大于那个,程序就会死掉.

以下是代码

package main

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

func exe_cmd(cmd string, wg *sync.WaitGroup) {
    fmt.Println(cmd)
    c = cmd.Str
    out, err := exec.Command(cmd).Output()
    if err != nil {
        fmt.Println("error occured")
        fmt.Printf("%s", err)
    }
    fmt.Printf("%s", out)
    wg.Done()
}

func main() {
    wg := new(sync.WaitGroup)
    wg.Add(3)

    x := []string{"echo newline >> foo.o", "echo newline >> f1.o", "echo newline >> f2.o"}
    go exe_cmd(x[0], wg)
    go exe_cmd(x[1], wg)
    go exe_cmd(x[2], wg)

    wg.Wait()
}
Run Code Online (Sandbox Code Playgroud)

以下是我看到的错误

exec: "echo newline >> foo.o": executable file not found …
Run Code Online (Sandbox Code Playgroud)

go

44
推荐指数
3
解决办法
9万
查看次数

标签 统计

go ×1