我正在关注 golang tutorial用于编写我的网络应用程序。我正在修改 tutorial page 中的代码,这样我就可以将保存的页面作为 go 代码执行(类似于 go playground )。但是当我尝试使用 os/exec
包执行保存的 go 文件时,它会抛出以下错误。
exec: "go run testcode.go": executable file not found in $PATH
以下是我修改后的代码:
// Structure to hold the Page
type Page struct {
Title string
Body []byte
Output []byte
}
// saving the page
func (p *Page) save() { // difference between func (p *Page) and func (p Page)
filename := p.Title + ".go"
ioutil.WriteFile(filename, p.Body, 0777)
}
// handle for the editing
func editHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/edit/"):]
p, err := loadPage(title)
if err != nil {
p = &Page{Title: title}
}
htmlTemp, _ := template.ParseFiles("edit.html")
htmlTemp.Execute(w, p)
}
// saving the page
func saveHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/save/"):]
body := r.FormValue("body")
p := Page{Title: title, Body: []byte(body)}
p.save()
http.Redirect(w, r, "/exec/"+title, http.StatusFound) // what is statusfound
}
// this function will execute the code.
func executeCode(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/exec/"):]
cmd := "go run " + title + ".go"
//cmd = "go"
fmt.Print(cmd)
out, err := exec.Command(cmd).Output()
if err != nil {
fmt.Print("could not execute")
fmt.Fprint(w, err)
} else {
p := Page{Title: title, Output: out}
htmlTemp, _ := template.ParseFiles("output.html")
htmlTemp.Execute(w, p)
}
}
请告诉我为什么我无法执行 go 文件。
最佳答案
您以错误的方式调用命令。第一个字符串是可执行文件的完整路径
os.exec.Command :func Command(name string, arg ...string)
所以你想要 exec.Command("/usr/bin/go", "run", title+".go")
关于go - 无法使用 os/exec 包执行 go 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27451697/