从Go调用Python函数并获取函数返回值

Bry*_*mas 12 python go

我正在写一个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")
}
Run Code Online (Sandbox Code Playgroud)

pythonfile.py

def cat_strings(a, b):
    return a + b
Run Code Online (Sandbox Code Playgroud)

如果我打电话给go run gofile我得到以下输出:

here we go...
command args: [python -c 'import pythonfile; print pythonfile.cat_strings("foo", "bar")']
concatentation length:  0
concatenation:  
...done
Run Code Online (Sandbox Code Playgroud)

几点说明:

  • -c在Python调用中使用该标志,因此我可以cat_strings直接调用该函数.假设cat_strings是一个Python文件的一部分,其中包含其他Python程序使用的实用程序函数,因此我没有任何if __name__ == __main__业务.
  • 我不想将Python文件修改为print a + b(而不是return a + b); 请参阅前面关于函数是一组实用函数的一部分的观点,这些函数函数应该可以被其他Python代码调用.
  • cat_strings功能是虚构的,用于演示目的; 真正的功能是我不想简单地在Go中重新实现.我真的很感兴趣我如何从Go调用Python函数并获得返回值.

val*_*val 10

我设法通过简单地删除命令本身的引用来为此创建一些代码:

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))
}
Run Code Online (Sandbox Code Playgroud)

当然,在源代码中,你有这个功能(对于Windows,至少,我不知道这是否适用于其他操作系统):

// EscapeArg rewrites command line argument s as prescribed
// in http://msdn.microsoft.com/en-us/library/ms880421.
// This function returns "" (2 double quotes) if s is empty.
// Alternatively, these transformations are done:
// - every back slash (\) is doubled, but only if immediately
//   followed by double quote (");
// - every double quote (") is escaped by back slash (\);
// - finally, s is wrapped with double quotes (arg -> "arg"),
//   but only if there is space or tab inside s.
func EscapeArg(s string) string { ...
Run Code Online (Sandbox Code Playgroud)

所以你的代码最终传递了以下命令行调用:

$ python -c "'import pythonfile; print pythonfile.cat_strings(\\"foo\\", \\"bar\\")'"
Run Code Online (Sandbox Code Playgroud)

如果经过测试,则评估为字符串并且不返回任何内容,因此输出0长度.

  • 太好了!乐于帮助.虽然正如其他人所建议的那样,如果要大量使用它,最好使用CPython API绑定或使用网络接口在Python和Go之间进行通信. (4认同)