英文:
Given an arbitrary string, how can I shell out the command to bash?
问题
我有一个相当基础的golang问题。
给定一个任意的字符串,比如"echo foo"或者"CGO_ENABLED=0 go build -o ./bin/echo -a main.go",使用os/exec解析和运行该命令的惯用方法是什么?
我目前的解决方法似乎有些笨拙,我正在寻找更加惯用的方法。
userInput := "CGO_ENABLED=0 go build -o ./bin/echo -a main.go"
command := exec.Command("/bin/bash", "-c", userInput)
out, err := command.Output()
if err != nil {
    fmt.Println(err)
}
英文:
I have a pretty basic golang question.
Given an arbitrary string like "echo foo", or "CGO_ENABLED=0 go build -o ./bin/echo -a main.go", what is the idiomatic way to parse/run that command using os/exec?
The way that I got this working seems pretty hacky, and I'm looking for a more idiomatic approach.
userInput = "CGO_ENABLED=0 go build -o ./bin/echo -a main.go"
command := exec.Command("/bin/bash", "-c", userInput)
out, err := command.Output()
if err != nil {
    fmt.Println(err)
 }
答案1
得分: 0
根据您的userInput字符串的任意性和灵活性,我可能会这样做。
package main
import (
	"log"
	"os"
	"os/exec"
)
func main() {
	if err := os.Setenv("FOO", "bar"); err != nil {
		log.Println(err)
	}
	// 正如Dave C指出的,exec.Command会为您执行此操作。
	// goAbsPath, err := exec.LookPath("go")
	// if err != nil {
	//	 log.Println(err)
	// }
	// 传递其他必要的参数。
	cmd := exec.Command("go", "version")
	if err := cmd.Run(); err != nil {
		log.Println(err)
	}
}
如果没有其他要求,也许了解os.Setenv和exec.LookPath可能会有用。
英文:
Depending on how arbitrary and flexible your userInput string is, I might do something like this.
package main
import (
	"log"
	"os"
	"os/exec"
)
func main() {
	if err := os.Setenv("FOO", "bar"); err != nil {
		log.Println(err)
	}
	// As Dave C pointed out, exec.Command does this for you.
	// goAbsPath, err := exec.LookPath("go")
	// if err != nil {
	//	 log.Println(err)
	// }
	// Pass whatever other arguments necessary.
	cmd := exec.Command("go", "version")
	if err = cmd.Run(); err != nil {
		log.Println(err)
	}
}
If nothing else, maybe os.Setenv and exec.LookPath might be useful to know about.
答案2
得分: 0
我可以这样写:
cmd := exec.Command(cmdName, arg1, arg2, ..)
cmd.Env = append(cmd.Env, "foo=bar")
err = cmd.Start()
if err != nil {
    // 记录日志或其他操作
}
err = cmd.Wait()
if err != nil {
    if exitErr, ok := err.(*exec.ExitError); ok {
        if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
            // 根据不同的 status.ExitStatus() 处理错误
        }
        // ...
    }
    // ...
}
// ...
如果需要更多细节,Godoc解释得很清楚。
英文:
I may write like this:
cmd := exec.Command(cmdName, arg1, arg2, ..)   
cmd.Env = append(cmd.Env, "foo=bar")
err = cmd.Start()
if err != nil {
    // log or something else
}
err = cmd.Wait()
if err != nil {
    if exitErr, ok := err.(*exec.ExitError); ok {
        if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
            // handle err according to different status.ExitStatus()
        }
        // ...
    }
    // ...
}
// ...
Godoc explains quite well if you need more details.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论