报错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执行
原文:https://www.cnblogs.com/aishanyishi/p/13432913.html