2017-04-06 01:04
浏览 75

如何从带空格的字符串创建os.exec Command结构

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

图片转代码服务由CSDN问答提供 功能建议

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

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

  cmd:= exec.Command(“ tr”,“ az”,“ AZ”)


  a:=字符串(“ ifconfig”)
cmd:= exec.Command(a)
output,err:= cmd.CombinedOutput()
fmt.Println(output)// 打印ifconfig输出


  a:=字符串(“ ifconfig -a”)
cmd  := exec.Command(a)
output,err:= cmd.CombinedOutput()
fmt.Println(output)//找不到'ifconfig -a'
 <  p>我尝试了strings.Split(a),但收到错误消息:exec.Command  
 的参数不能使用([] string)作为类型字符串
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题