如何从带有空格的字符串创建 os.exec 命令结构
时间:2023-04-25
浏览:433
作者:佚名
今天golang学习网给大家带来了《如何从带有空格的字符串创建 os.exec 命令结构》,其中涉及到的知识点包括golang等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~
问题内容
我希望我的方法接收一个以字符串形式执行的命令。如果输入字符串有空格,如何将其拆分为 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) 作为类型字符串
正确答案
请查看: 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)
理论要掌握,实操不能落!以上关于《如何从带有空格的字符串创建 os.exec 命令结构》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
11.29
热门专题
