duanbo6482 2013-12-07 03:50
浏览 91
已采纳

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

I have a bunch of systems commands which are somwhat similar to appending new content to a file. I wrote a simple script to execute system commands, which works well if there are single words like 'ls' , 'date' etc. But if the command is greater than that, program dies.

The following is the code

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()
}

The following is the error i see

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 

I guess, this may be due to, not sending cmds and arguments seperately ( http://golang.org/pkg/os/exec/#Command ) . I am wondering how to subvert this , since I dunno how many arguments will be there in my command which needs to be executed.

  • 写回答

5条回答 默认 最新

  • dousu8456 2013-12-07 06:00
    关注

    I found a relatively decent way to achieve the same .

    out, err := exec.Command("sh","-c",cmd).Output()
    

    Works for me until now. Still finding better ways to achieve the same.

    Edit1:

    Finally a easier and efficient (atleast so far) way to do would be like this

    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
    }
    

    Thanks to variadic arguments in go and people that pointed that out to me :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算