第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

無法使用 os/exec 包執(zhí)行 go 文件

無法使用 os/exec 包執(zhí)行 go 文件

Go
達令說 2021-09-09 21:46:15
我正在按照golang 教程編寫我的 Web 應(yīng)用程序。我正在修改教程頁面中的代碼,以便我可以將保存的頁面作為 go 代碼執(zhí)行(類似于go playground)。但是當(dāng)我嘗試使用該os/exec包執(zhí)行保存的 go 文件時,它會引發(fā)以下錯誤。exec: "go run testcode.go": 在 $PATH 中找不到可執(zhí)行文件以下是我修改后的代碼:// 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)    }}請告訴我為什么我無法執(zhí)行 go 文件。
查看完整描述

2 回答

?
繁星點點滴滴

TA貢獻1803條經(jīng)驗 獲得超3個贊

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

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

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


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

TA貢獻1799條經(jīng)驗 獲得超6個贊

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


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


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


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


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

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

然后你的程序?qū)⒃?ubuntu 和 RHEL 中執(zhí)行。


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


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


查看完整回答
反對 回復(fù) 2021-09-09
  • 2 回答
  • 0 關(guān)注
  • 330 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號