如何将 golang 与 python 集成?安装 golang 和 python。配置 gopath 环境变量。安装 cgo golang 包。创建 golang 项目。为 python 组件编写 golang wrapper 函数。在 python 项目中创建模块。使用 cgo 构建 golang 项目。在 golang 代码中调用 python 函数。运行 golang 程序。
Golang 框架与 Python 集成
有时,您可能需要在 Golang 应用程序中使用 Python 组件。本指南将向您展示如何将 Golang 与 Python 集成,并提供一个实战案例。
先决条件
立即学习“Python免费学习笔记(深入)”;
- 安装 Golang 和 Python
- 配置 GOPATH 环境变量
- 安装名为 cgo 的 Golang 包
步骤
- 创建 Golang 项目
mkdir golang-python-integration && cd golang-python-integration
- 编写 Golang wrapper
为 Python 组件创建一个 Golang wrapper 函数。这将允许您在 Golang 代码中调用 Python 函数。
// mypython.go
package main
/*
#include <Python.h>
static PyObject* call_python_function(char* func_name) {
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
pName = PyUnicode_DecodeFSDefault(func_name);
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "my_function");
pValue = PyObject_CallObject(pFunc, NULL);
return pValue;
}
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
result := C.call_python_function(C.CString("my_function"))
fmt.Println(C.GoString(result))
}
- 编写 Python 模块
在 Python 项目中创建 my_function 模块。
# my_function.py
def my_function():
return "Hello from Python!"
- 构建 Golang 项目
使用 cgo 构建 Golang 项目。它将允许 Golang 程序调用 C 代码,后者又将调用 Python 代码。
go build -buildmode=c-shared -o mypython.so mypython.go
- 调用 Python 函数
在 Golang 代码中,您可以现在调用 Python 函数。
package main
import (
"fmt"
"log"
"syscall"
"unsafe"
)
func main() {
// Load the shared library.
lib, err := syscall.LoadDLL("mypython.so")
if err != nil {
log.Fatal(err)
}
defer lib.Release()
// Get the function pointer.
callPythonFunction, err := lib.FindProc("call_python_function")
if err != nil {
log.Fatal(err)
}
// Call the Python function.
result, _, err := callPythonFunction.Call(
uintptr(unsafe.Pointer(syscall.StringBytePtr("my_function"))),
)
if err != nil {
log.Fatal(err)
}
// Print the result.
fmt.Println(syscall.UTF16ToString((*[1 << 30]uint16)(unsafe.Pointer(result))[:]))
}
运行
运行 Golang 程序。
go run main.go
输出
Hello from Python!
您现在已成功将 Golang 与 Python 集成,并调用了 Python 函数。