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

时间:2016-10-04 00:00:11

标签: python go

在我的Go文件中,我使用exec来运行外部脚本:

var requests = $.when.apply(null, teams.map(function(team) {
  return $.ajax({
            url: url + team + ".json",
            type: 'GET',
            success: function(response){
                processPlayerNames(response, logObj);
            }
        });
}));

requests.then(function() {
  writeLog(logObj)
}, function(response){
  console.log(response);
});

python脚本执行得很好,但go cmd := exec.Command("test.py") out, err := cmd.CombinedOutput() if err != nil { fmt.Println(err) } fmt.Println(string(out)) 没有打印任何内容。

问题是我应该如何从Python脚本返回值以便从Go再次回读?

Python伪代码:

fmt.Println(string(out))

1 个答案:

答案 0 :(得分:-1)

我想我发现了这个错误,你需要把完整的路径放到" test.py"

<强>测试

我在目录中有两个文件:     test.py     test.go

test.py是:

#!/usr/bin/env python3

print("Hello from python")

test.go是:

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))
}

我得到以下输出:

$ go run ./test.go 
Hello from python