如何从带有空格的字符串创建一个 os.exec 命令结构体?

huangapple go评论86阅读模式
英文:

How to create an os.exec Command struct from a string with spaces

问题

我想让我的方法接收一个作为字符串的命令来执行。如果输入的字符串中有空格,我该如何将其拆分为用于 os.exec 的 cmd 和 args?

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

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

这个方法可以正常工作:

a := string("ifconfig")
cmd := exec.Command(a)
output, err := cmd.CombinedOutput()
fmt.Println(output) // 打印 ifconfig 的输出

但是这个方法失败了:

a := string("ifconfig -a")
cmd := exec.Command(a)
output, err := cmd.CombinedOutput()
fmt.Println(output) // 打印 'ifconfig -a' 未找到

我尝试了 strings.Split(a),但收到一个错误消息:无法将 []string 类型用作 exec.Command 的参数中的 string 类型。

英文:

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

答案1

得分: 17

args := strings.Fields("ifconfig -a ")
exec.Command(args[0], args[1:]...)

strings.Fields()函数根据空格分割字符串,并返回一个切片

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

英文:
args := strings.Fields("ifconfig  -a ")
exec.Command(args[0], args[1:]...)

strings.Fields() splits on whitespace, and returns a slice

... expands slice into individual string arguments

答案2

得分: 8

请查看:
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: 处理错误
}
cmd := exec.Command(command[0], command[1:]...)
stdoutStderr, err := cmd.CombinedOutput()
if err != nil {
	// TODO: 更优雅地处理错误
	log.Fatal(err)
}
// 处理输出
fmt.Printf("%s\n", stdoutStderr)
英文:

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(&quot;ifconfig -a&quot;, &quot; &quot;)
if len(command) &lt; 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(&quot;%s\n&quot;, stdoutStderr)

答案3

得分: 0

我喜欢这样使用exec.Command()

args := []string{
  "-l",
  fmt.Sprintf(xxxxx),
}
cmd := exec.Command("ls", args...)
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
英文:

I like to use the exec.Command() like this:

args=[]string{
  &quot;-l&quot;,
  fmt.Sprintf(xxxxx),
}
cmd := exec.Command(&quot;ls&quot;, args...)
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr

huangapple
  • 本文由 发表于 2017年4月6日 09:04:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/43243995.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定