无法使用os/exec包执行go文件 [英] Not able to execute go file using os/exec package
问题描述
我正在遵循 golang教程来编写我的Web应用程序.我正在修改教程页面中的代码,以便可以将保存的页面作为go代码执行(类似于去游乐场).但是,当我尝试使用 os/exec
包执行保存的go文件时,会引发以下错误.
I am following the golang tutorial for writing my web app. I am modifying the code from tutorial page, so that I can execute the saved page as go code (similar to go playground). But when I try to execute the saved go file using the os/exec
package, it throws the following error.
exec:运行run testcode.go":在$ PATH中找不到可执行文件
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文件.
Please tell me why I am not able to able to execute the go file.
推荐答案
您以错误的方式调用命令.第一个字符串是可执行文件的完整路径
You are invoking command in the wrong way. The first string is the full path to the executable
os.exec.Command : func Command(名称字符串,arg ... string)
所以你想要 exec.Command("/usr/bin/go","run",title +.go")
这篇关于无法使用os/exec包执行go文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!