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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵