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

时间:2013-10-16 07:56:07

标签: 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")
}

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函数并获得返回值。

1 个答案:

答案 0 :(得分: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))
}

果然,在source中你有这个功能(对于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 { ...

因此,您的代码最终会通过以下命令行调用:

$ python -c "'import pythonfile; print pythonfile.cat_strings(\\"foo\\", \\"bar\\")'"

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

相关问题