在Golang代码中使用Python的方法
在Golang代码中使用Python的方法 我需要在我的Go代码中使用Python代码。 我写了以下示例,但无法运行它:
package main
// #cgo pkg-config: python3
// #include "/usr/include/python3.11/Python.h"
import "C"
import "fmt"
func main() {
C.Py_Initialize()
fmt.Println(C.GoString(C.Py_GetVersion()))
C.Py_Finalize()
}
链接器错误
# command-line-arguments
/usr/local/go/pkg/tool/linux_amd64/link: running gcc failed: exit status 1
/usr/bin/ld: /tmp/go-link-3756148642/000001.o: in function `_cgo_d10853a22200_Cfunc_Py_GetVersion':
/tmp/go-build/cgo-gcc-prolog:63: undefined reference to `Py_GetVersion'
/usr/bin/ld: /tmp/go-link-3756148642/000001.o: in function `_cgo_d10853a22200_Cfunc_Py_Finalize':
/tmp/go-build/cgo-gcc-prolog:49: undefined reference to `Py_Finalize'
/usr/bin/ld: /tmp/go-link-3756148642/000001.o: in function `_cgo_d10853a22200_Cfunc_Py_Initialize':
/tmp/go-build/cgo-gcc-prolog:78: undefined reference to `Py_Initialize'
collect2: error: ld returned 1 exit status
操作系统:Fedora release 37 (Thirty Seven) Go版本:go version go1.19.5 linux/amd64 Python版本:Python 3.11.1 gcc版本:gcc (GCC) 12.2.1 20221121 (Red Hat 12.2.1-4)
更多关于在Golang代码中使用Python的方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html
6 回复
我猜Go找不到libpython3。你的python3.pc文件内容是什么?
更多关于在Golang代码中使用Python的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
遗憾的是,它仍然无法工作。
我从未这样做过,但我想 Libs 或 Libs.private 中应该包含 -lpython3。
哦,明白了!
python3-embed Python - 将Python嵌入到应用程序中
python3 Python - 为Python构建C扩展
我需要的是 python3-embed,而不是 python3。
以下是 /usr/lib64/pkgconfig/python3.pc 文件的内容:
# See: man pkg-config
prefix=/usr
exec_prefix=/usr
libdir=/usr/lib64
includedir=/usr/include
Name: Python
Description: Build a C extension for Python
Requires:
Version: 3.11
Libs.private: -ldl
Libs:
Cflags: -I${includedir}/python3.11


