我正在編寫一個(gè)Go程序。在這個(gè) Go 程序中,我想調(diào)用另一個(gè)文件中定義的 Python 函數(shù)并接收該函數(shù)的返回值,以便我可以在 Go 程序的后續(xù)處理中使用它。但是,我無法在 Go 程序中獲取任何返回的數(shù)據(jù)。以下是我認(rèn)為可行但顯然不可行的最小示例:gofile.gopackage mainimport "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")}蟒蛇文件.pydef cat_strings(a, b): return a + b如果我打電話,go run gofile我會(huì)得到以下輸出:here we go...command args: [python -c 'import pythonfile; print pythonfile.cat_strings("foo", "bar")']concatentation length: 0concatenation: ...done一些注意事項(xiàng):我-c在 Python 調(diào)用中使用了該標(biāo)志,因此我可以cat_strings直接調(diào)用該函數(shù)。假設(shè)cat_strings是 Python 文件的一部分,其中包含其他 Python 程序使用的實(shí)用函數(shù),因此我沒有任何if __name__ == __main__業(yè)務(wù)。我不想將 Python 文件修改為print a + b(而不是return a + b);請參閱關(guān)于該函數(shù)是一組實(shí)用程序函數(shù)的一部分的先前觀點(diǎn),這些函數(shù)應(yīng)該可以被其他 Python 代碼調(diào)用。該cat_strings函數(shù)是虛構(gòu)的,用于演示目的;真正的功能是我不想簡單地在 Go 中重新實(shí)現(xiàn)的東西。我真的對如何從 Go 調(diào)用 Python 函數(shù)并獲取返回值感興趣。
- 1 回答
- 0 關(guān)注
- 527 瀏覽
添加回答
舉報(bào)
0/150
提交
取消