亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法使用 os/exec 包執行 go 文件

無法使用 os/exec 包執行 go 文件

Go
達令說 2021-09-09 21:46:15
我正在按照golang 教程編寫我的 Web 應用程序。我正在修改教程頁面中的代碼,以便我可以將保存的頁面作為 go 代碼執行(類似于go playground)。但是當我嘗試使用該os/exec包執行保存的 go 文件時,它會引發以下錯誤。exec: "go run testcode.go": 在 $PATH 中找不到可執行文件以下是我修改后的代碼:// Structure to hold the Pagetype Page struct {    Title  string    Body   []byte    Output []byte}// saving the pagefunc (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 editingfunc 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 pagefunc 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 文件。
查看完整描述

2 回答

?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

您以錯誤的方式調用命令。第一個字符串是可執行文件的完整路徑

os.exec.Commandfunc Command(name string, arg ...string)

所以你要 exec.Command("/usr/bin/go", "run", title+".go")


查看完整回答
反對 回復 2021-09-09
?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

接受的答案指出os.exec.Command的第一個參數是可執行文件的完整路徑。從文檔:


“如果名稱不包含路徑分隔符,如果可能,Command 使用 LookPath將路徑解析為完整名稱。否則直接使用名稱”。


executable file not found in $PATH除了像之前建議的那樣在可執行文件名稱之后傳遞參數之外,您還應該做些什么來避免錯誤,那PATH就是在您的 SHELL 中或使用os.Setenv設置您的參數。如果您對命令的完整位置進行硬編碼,則您的程序可能無法移植到另一個 Unix 操作系統。


例如,該命令lspci位于下/usr/bin在Ubuntu和下/sbin/在RHEL。如果你這樣做:


os.Setenv("PATH", "/usr/bin:/sbin")

exec.Command("lspci", "-mm")

然后你的程序將在 ubuntu 和 RHEL 中執行。


或者,形成外殼,您還可以執行以下操作: PATH=/sbin; my_program


注意:上述命令僅限PATH于明確指示的路徑。例如,如果要添加到 shell 中的現有路徑,請執行PATH=/sbin:$PATH; my_program; 在 go 中,您可能可以使用 讀取變量,os.Getenv然后在執行os.Setenv.


查看完整回答
反對 回復 2021-09-09
  • 2 回答
  • 0 關注
  • 375 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號