go gin框架呼叫cmd執行python指令碼問題
阿新 • • 發佈:2020-08-04
報錯1:exec: "python3 test.py": executable file not found in $PATH
在單個go程式中直接執行以下指令碼沒有問題
func TestCmdPython(t *testing.T) { //test.txt的內容為圖片的base64字串 //filePath := "test.txt" //newFileName := "test.jpg" //CmdPythonSaveImageDpi(filePath,newFileName) cmd := exec.Command("python3 test.py")//cmd.Dir, _ = os.Getwd() fmt.Println("cmd.Path:",cmd.Path) fmt.Println("cmd.Dir:",cmd.Dir) //out,err := cmd.Output() }
但是在gin中開啟子執行緒去執行指令碼,就會有報錯1的出現
go diffPython()
func diffPython(result1, result2 string,scope string) bool { //args := []string{} fmt.Println(os.Getwd()) cmd := exec.Command("python3 ./script/test.py") fmt.Println("cmd.Path:",cmd.Path) fmt.Println("cmd.Dir:",cmd.Dir) out,err := cmd.Output() if err != nil { fmt.Println("diffPython:",err) } result := string(out) fmt.Println(result) //if strings.Index(result, "success") != 0 { // err = errors.New(fmt.Sprintf("main.py error:%s", result))//} res, _ := strconv.ParseBool(result) return res }
1.gin執行後當前目錄為專案的目錄,而不是go檔案所在的目錄
2.gin中的exec.Commond會將python3 test.py識別為一整個命令,而不是python3 +引數
解決方案,將python和執行檔案分開
//執行python指令碼 func diffPython(result1, result2 string,scope string) bool { //args := []string{} fmt.Println(os.Getwd()) cmd := exec.Command("python3","./script/test.py") fmt.Println("cmd.Path:",cmd.Path) fmt.Println("cmd.Dir:",cmd.Dir) out,err := cmd.Output() if err != nil { fmt.Println("diffPython:",err) } result := string(out) fmt.Println(result) //if strings.Index(result, "success") != 0 { // err = errors.New(fmt.Sprintf("main.py error:%s", result)) //} res, _ := strconv.ParseBool(result) return res }
其中還會有一個報錯 exit status 1,是因為我的指令碼為python3的不能用python -dir執行