如何使用带空格的字符串创建os.exec Command结构 [英] How to create an os.exec Command struct from a string with spaces

查看:47
本文介绍了如何使用带空格的字符串创建os.exec Command结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的方法接收以字符串形式执行的命令.如果输入字符串中有空格,如何将其拆分为os.exec的cmd,args?

文档说要像这样创建我的Exec.Cmd结构

  cmd:= exec.Command("tr","a-z","A-Z") 

这很好:

  a:=字符串("ifconfig")cmd:= exec.Command(a)输出,错误:= cmd.CombinedOutput()fmt.Println(output)//打印ifconfig输出 

此操作失败:

  a:=字符串("ifconfig -a")cmd:= exec.Command(a)输出,错误:= cmd.CombinedOutput()fmt.Println(output)//找不到'ifconfig -a' 

我尝试了strings.Split(a),但收到一条错误消息:exec.Command的参数不能使用([] string)作为类型字符串

解决方案

请签出: https://golang.org/pkg/os/exec/#example_Cmd_CombinedOutput

您的代码失败,因为 exec.Command 期望命令参数与实际的命令名称分开.

strings.Split 签名( https://golang.org/pkg/strings/#Split ):

  func Split(s,sep string)[] string 

您试图实现的目标:

 命令:= strings.Split("ifconfig -a",")如果len(command)<2 {//TODO:处理错误}cmd:= exec.Command(命令[0],命令[1:] ...)stdoutStderr,err:= cmd.CombinedOutput()如果err!= nil {//TODO:更优雅地处理错误log.Fatal(错误)}//对输出做一些事情fmt.Printf(%s \ n",stdoutStderr) 

I want my method to receive a command to exec as a string. If the input string has spaces, how do I split it into cmd, args for os.exec?

The documentation says to create my Exec.Cmd struct like

cmd := exec.Command("tr", "a-z", "A-Z")

This works fine:

a := string("ifconfig")
cmd := exec.Command(a)
output, err := cmd.CombinedOutput()
fmt.Println(output) // prints ifconfig output

This fails:

a := string("ifconfig -a")
cmd := exec.Command(a)
output, err := cmd.CombinedOutput()
fmt.Println(output) // 'ifconfig -a' not found

I tried strings.Split(a), but receive an error message: cannot use (type []string) as type string in argument to exec.Command

解决方案

Please, check out: https://golang.org/pkg/os/exec/#example_Cmd_CombinedOutput

Your code fails because exec.Command expects command arguments to be separated from actual command name.

strings.Split signature (https://golang.org/pkg/strings/#Split):

func Split(s, sep string) []string

What you tried to achieve:

command := strings.Split("ifconfig -a", " ")
if len(command) < 2 {
    // TODO: handle error
}
cmd := exec.Command(command[0], command[1:]...)
stdoutStderr, err := cmd.CombinedOutput()
if err != nil {
    // TODO: handle error more gracefully
    log.Fatal(err)
}
// do something with output
fmt.Printf("%s\n", stdoutStderr)

这篇关于如何使用带空格的字符串创建os.exec Command结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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