在Python程序中从Github导入Golang模块



我有一个用Python (.py)编写的程序,它需要导入和使用位于Github repo中的Golang (.go)包编写的函数。

如何在python代码中导入。go包模块并使用该函数?该函数应该从我的python代码中接受参数,并在执行一些操作后返回一个值。

注意:我想在Python2.7版本中实现这一点。

go_file.go

// Utility function to get string formed from input list of strings.
func NewFromStrings(inputs []string) string {
// do something
return "abc"
}

python_file.py

# This is just a pseudo code to make problem statement more clear.
import github.com/path_to_package/go_file
str_list = ['abc', 'def']
result = go_file.NewFromStrings(str_list)
print(result)

Thanks in advance:)

您有几个选项,但是不需要做一点工作就可以直接从python导入Go代码。

  • 要做你在评论中链接的问题的相反,你可以创建一个小的go命令行来暴露你的go函数。然后你可以使用subprocess.run从python执行这个Go命令行。然后可以从标准输出访问结果。看到https://docs.python.org/3/library/subprocess.html subprocess.run

  • 或者,您可以使用IPC进行通信,如套接字,这将涉及在Go中创建一个小服务器。

  • 我能想到的第三个选项是在本机库中导出Go函数并使用c绑定从python调用它。这可能是最复杂的路径,但会让你最接近于能够从python中导入go代码。

查看这篇博客文章,其中有一些选项的更彻底的分解:https://www.ardanlabs.com/blog/2020/06/python-go-grpc.html

最新更新