从Go调用Python函数并获取函数返回值
我正在写一个程序。在这个Go程序中,我想调用另一个文件中定义的Python函数,并接收该函数的返回值,以便在我的Go程序的后续处理中使用它。但是,我很难在我的Go程序中获取任何返回的数据。下面是一个我认为可行但显然行不通的最起码的例子: gofile.go从Go调用Python函数并获取函数返回值,python,go,Python,Go,我正在写一个程序。在这个Go程序中,我想调用另一个文件中定义的Python函数,并接收该函数的返回值,以便在我的Go程序的后续处理中使用它。但是,我很难在我的Go程序中获取任何返回的数据。下面是一个我认为可行但显然行不通的最起码的例子: gofile.go package main import "os/exec" import "fmt" func main() { fmt.Println("here we go...") program := "python"
package main
import "os/exec"
import "fmt"
func main() {
fmt.Println("here we go...")
program := "python"
arg0 := "-c"
arg1 := fmt.Sprintf("'import pythonfile; print pythonfile.cat_strings(\"%s\", \"%s\")'", "foo", "bar")
cmd := exec.Command(program, arg0, arg1)
fmt.Println("command args:", cmd.Args)
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("Concatenation failed with error:", err.Error())
return
}
fmt.Println("concatentation length: ", len(out))
fmt.Println("concatenation: ", string(out))
fmt.Println("...done")
}
pythonfile.py
def cat_strings(a, b):
return a + b
如果我调用go run gofile
,我会得到以下输出:
here we go...
command args: [python -c 'import pythonfile; print pythonfile.cat_strings("foo", "bar")']
concatentation length: 0
concatenation:
...done
请注意:
- 我在Python调用中使用了
标志,因此我可以直接调用函数-c
。假设cat\u strings
是一个Python文件的一部分,该文件包含其他Python程序使用的实用函数,因此,如果uuuu name_uuuuu==uuuuu main_uuu业务,为什么我没有任何cat_strings
- 我不想将Python文件修改为
(而不是打印a+b
);请参阅前面的一点,该函数是一组实用函数的一部分,其他Python代码应该可以调用这些实用函数返回a+b
函数是虚构的,用于演示;真正的函数是我不想在Go中简单地重新实现的。我对如何从Go调用Python函数并获得返回值非常感兴趣cat_strings
package main
import "fmt"
import "os/exec"
func main() {
cmd := exec.Command("python", "-c", "import pythonfile; print pythonfile.cat_strings('foo', 'bar')")
fmt.Println(cmd.Args)
out, err := cmd.CombinedOutput()
if err != nil { fmt.Println(err); }
fmt.Println(string(out))
}
果然,在中,您有这个功能(至少对于Windows,我不知道这是否适用于其他操作系统):
因此,您的代码最终将通过以下命令行调用:
$ python -c "'import pythonfile; print pythonfile.cat_strings(\\"foo\\", \\"bar\\")'"
如果对其进行测试,则其计算结果为字符串且不返回任何内容,因此为0长度输出。我感觉使用
os/exec
很难做到这一点。所有的os/exec
函数只返回stdout和/或stderr;打印pythonfile。cat_字符串(“foo”,“bar”)”将打印到stdout。它是否在您刚刚运行python-c“导入pythonfile”时打印;从命令提示符打印pythonfile.cat_字符串(“foo”、“bar”)
?如果它输出到stdout(或stderr),那么它应该在os/exec上工作。@Intermernet是的,它可以,这就是为什么我觉得奇怪的是,Go似乎没有收到刚刚在Linux(Ubuntu)上测试过的结果,并且删除了单引号,这似乎是一个跨平台的解决方案。很好!很乐意帮忙。尽管正如其他人所建议的,如果要大量使用它,最好使用cpythonapi绑定或使用网络接口在Python和Go之间进行通信。
$ python -c "'import pythonfile; print pythonfile.cat_strings(\\"foo\\", \\"bar\\")'"