看网上有很多go调用Python的资料,但鱼龙混杂,很多还是Python2的,因此,亲测一把,做个记录。
微信公众号:leetcode_algos_life 前提条件
https://github.com/DataDog/go-python3
conda create -n pygo python=3.7
测试

go代码(main.go)

package main

import "github.com/DataDog/go-python3"

func main() {

        defer python3.Py_Finalize()
        python3.Py_Initialize()
        python3.PyRun_SimpleString("print('hello from python in go')")

}

然后执行:

go mod tiny
go run main.go
错误信息及解决方案

错误信息:

go/pkg/tool/linux_amd64/link: running gcc failed: exit status 1
/usr/bin/ld: cannot find -lpython3.7m
collect2: error: ld returned 1 exit status

解决方案:

rm -rf ~/.cache/go-build
export CXXFLAGS="-stdlib=libstdc++" CC=/usr/bin/gcc CXX=/usr/bin/g++

接着报错,报错信息

export PKG_CONFIG_PATH=gopy(你自己创建的虚拟环境路径)/lib/pkgconfig
go get github.com/DataDog/go-python3
go  mod  tidy
go run main.go
hello from python in go

over