Use python in GO code

Hi!
I need to use python code in go.
I wrote the following example but I am unable to run it:

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()
}
ld panic
# 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

OS: 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)

I’m guessing Go can’t find libpython3. What does your python3.pc file look like?

@skillian here is content of /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

I’ve never done this before, butI would think Libs or Libs.private should have -lpython3 in there.

sadly, it still does not work

Oh, got it!

python3-embed                  Python - Embed Python into an application
python3                        Python - Build a C extension for Python

I need python3-embed - not python3

2 Likes