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

  • 相关阅读:
    docker-redis
    docker-nginx
    docker-tomcat
    JQuery/JS插件 jsTree加载树,预先加载,初始化时加载前三级节点,当展开第三级节点时 就加载该节点下的所有子节点
    Python json
    Python 模拟鼠标
    Python 取列表的前几个
    winfrom 图片等比例压缩
    winfrom 改变图片透明度 Alpha
    winform 实现类似于TrackBar的自定义滑动条,功能更全
  • 原文地址:https://www.cnblogs.com/aishanyishi/p/13432913.html
Copyright © 2011-2022 走看看