如何使用未知参数执行系统命令 [英] How to execute system command with unknown arguments

查看:59
本文介绍了如何使用未知参数执行系统命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆系统命令,它们类似于将新内容附加到文件中.我编写了一个简单的脚本来执行系统命令,如果有单个单词,例如"ls","date"等,该脚本就可以很好地工作.但是如果命令大于此范围,程序就会死掉.

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.

以下是代码

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 

我想,这可能是由于未单独发送cmd和参数( http: //golang.org/pkg/os/exec/#Command ).我想知道如何颠覆这一点,因为我不知道命令中将要执行多少个参数.

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.

推荐答案

我找到了一种相对不错的方法来实现这一目标.

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
}

感谢go中各种各样的争论,还有向我指出的人:)

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

这篇关于如何使用未知参数执行系统命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆