【问题标题】:How to create an os.exec Command struct from a string with spaces如何从带空格的字符串创建 os.exec 命令结构
【发布时间】:2017-04-06 01:04:38
【问题描述】:

我希望我的方法接收一个以字符串形式执行的命令。如果输入字符串有空格,如何拆分成cmd、args for os.exec?

文档说要创建我的 Exec.Cmd 结构,如

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

这很好用:

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

这失败了:

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

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

【问题讨论】:

  • 您错误地使用了 strings.Split() golang.org/pkg/strings/#Split 您需要提供一个分隔符。所以.. strings.Split(a, " ") 在单个空格上拆分,其次,您不能拆分切片,因为它已经拆分,因此您的变量“a”已经是切片,而不是字符串。最后,您还可以定义切片而不是拆分字符串。 a := []string{"inconfig", "a"}.
  • 如果参数包含空格,这不会中断吗?

标签: go


【解决方案1】:
args := strings.Fields("ifconfig  -a ")
exec.Command(args[0], args[1:]...)

strings.Fields() 在空白处分割,并返回一个切片

... 将切片扩展为单独的字符串参数

【讨论】:

  • 这不是一个通用的解决方案,如果参数本身包含空格,则会失败。
【解决方案2】:

请检查: 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

你试图达到的目标:

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)

【讨论】:

  • @kostix 不,它不会工作。文档说:func Command(name string, arg ...string) *Cmd - 因此你必须单独传递第一个参数(命令名)。否则会产生错误:not enough arguments in call to exec.Command。我在@Mark 回答下指出了这一点,因为他犯了同样的错误。
猜你喜欢
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多