【发布时间】:2013-10-24 05:55:36
【问题描述】:
我正在编写一个Go 程序。从这个 Go 程序中,我想调用另一个文件中定义的 Python 函数并接收该函数的返回值,以便我可以在 Go 程序的后续处理中使用它。不过,我无法在我的 Go 程序中获取任何返回的数据。以下是我认为可行但显然行不通的最小示例:
gofile.go
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_strings。假设cat_strings是一个 Python 文件的一部分,其中包含其他 Python 程序使用的实用函数,因此我没有任何if __name__ == __main__业务。 - 我不想将Python文件修改为
print a + b(而不是return a + b);请参阅前面的观点,该函数是一组实用函数的一部分,应该可由其他 Python 代码调用。 -
cat_strings函数是虚构的,用于演示目的;真正的功能是我不想简单地在 Go 中重新实现的东西。我对如何从 Go 调用 Python 函数并获取返回值非常感兴趣。
【问题讨论】:
-
我感觉使用
os/exec不容易做到这一点。所有os/exec函数仅返回标准输出和/或标准错误。 -
@Intermernet 我以为我在
python -c 'import pythonfile; print pythonfile.cat_strings("foo", "bar")'中对print的调用会打印到标准输出。 -
当您从命令提示符运行
python -c 'import pythonfile; print pythonfile.cat_strings("foo", "bar")'时是否打印?如果它输出到标准输出(或标准错误),那么它应该从 os/exec 工作。 -
@Intermernet 是的,这就是为什么我觉得奇怪的是 Go 似乎没有收到结果