微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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()
}

以下是我看到的错误

exec: "echo newline >> foo.o": executable file not found in $PATHexec: 
"echo newline >> f2.o": executable file not found in $PATHexec: 
"echo newline >> f1.o": executable file not found in $PATH

我猜,这可能是因为,不单独发送cmds和论据(http://golang.org/pkg/os/exec/#Command)。我想知道如何颠覆这个,因为我不知道我的命令中将有多少个参数需要执行。

我发现一个比较体面的方式来实现这一点。
out,err := exec.Command("sh","-c",cmd).Output()

为我工作,直到现在。仍然找到更好的方式来实现这一点。

EDIT1:

最后一个更简单和高效(至少到目前为止)的做法就是这样

func exe_cmd(cmd string,wg *sync.WaitGroup) {
  fmt.Println("command is ",cmd)
  // splitting head => g++ parts => rest of the command
  parts := strings.Fields(cmd)
  head := parts[0]
  parts = parts[1:len(parts)]

  out,err := exec.Command(head,parts...).Output()
  if err != nil {
    fmt.Printf("%s",err)
  }
  fmt.Printf("%s",out)
  wg.Done() // Need to signal to waitgroup that this goroutine is done
}

感谢你们中的各种各样的论据,并指出我的人:)

原文地址:https://www.jb51.cc/go/187264.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐