go - 无法使用 os/exec 包执行 go 文件

标签 go

我正在关注 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/

相关文章:

go - 从字符串值更新 map[string]int

go - 为什么我不能在 Go 中用一种类型的 slice 替换另一种类型?

go - 如何使用 Godep 将我的 Go 应用程序部署到 heroku?

amazon-web-services - 使用 AWS EC2 Golang GO 端点在 Docker 部署上获取 JSON 时出现问题

mysql - 我可以在 Go 中参数化 create 语句吗?

go - 如何实现两个具有相同方法名和不同参数的接口(interface)

JSON 数组编码

go - 合并多个 go 模块的测试覆盖率

elasticsearch - 如何有效地只获取文档的一个字段进行 Elasticsearch

go - 使用代理连接到 Google Cloud SQL——错误 403 : Insufficient Permission