dongzhi1822 2016-10-04 00:00
浏览 1025

执行exec外部python脚本并获取返回的输出

In my Go file i use exec to run the external script:

cmd := exec.Command("test.py")
out, err := cmd.CombinedOutput()
if err != nil {
    fmt.Println(err)
}
fmt.Println(string(out))

The python script it's executed fine, but the go fmt.Println(string(out)) prints nothing.

The question it's how i should return the value from the Python script to be read back again from Go?

Python pseudo code:

def main(): ... ... return value

  • 写回答

1条回答 默认 最新

  • duanjiancong4860 2016-10-04 00:24
    关注

    I think i found the bug, you need to put the full path to "test.py"

    Test

    I have two files in a directory: test.py test.go

    The test.py is:

    #!/usr/bin/env python3
    
    print("Hello from python")
    

    and test.go is:

    package main
    
    import (
            "fmt"
            "os/exec"
    )
    
    func main() {
    
    //cmd := exec.Command("test.py")
    // I got an error because test.py was not in my PATH, which makes sense
    // When i added './' the program worked because go knew where to find test.py
    cmd := exec.Command("./test.py")
    out, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(out))
    }
    

    And I get the following output:

    $ go run ./test.go 
    Hello from python
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?