zoukankan      html  css  js  c++  java
  • go gin框架调用cmd运行python脚本问题

    报错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执行

  • 相关阅读:
    结对 总结
    ”耐撕“团队 2016.3.29 站立会议
    词频统计 List Array
    基本数据结构简述
    深入理解HashMap
    常用排序算法Java实现
    Spring核心组件知识梳理
    HashMap中使用自定义类作为Key时,为何要重写HashCode和Equals方法
    Nginx是什么东东?
    Java中常用的四种线程池
  • 原文地址:https://www.cnblogs.com/aishanyishi/p/13432913.html
Copyright © 2011-2022 走看看