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

  • 相关阅读:
    redis学习
    win2008下c#调用directshow问题
    vs2005升级到vs2010相关问题
    spark-shell 启动失败,显示端口问题
    监控spark-sql 等脚本
    spark 相关配置 shuffle 相关配置选项
    spark on Yarn 语句
    使用hive thriftserver 连接spark sql
    HBase 报错系列之region is not online
    HBase 表迁移中对丢失的表检查使用的语句
  • 原文地址:https://www.cnblogs.com/aishanyishi/p/13432913.html
Copyright © 2011-2022 走看看