确保python版本为3.7
conda create go_python python=3.7
conda activate go_python
确保python和go的架构一致
.mac中使用go的amd64版本也就是intel的x86
我的go_x86安装路径:/Users/gxy/sdk/go_x86_1.19
进入这个文件夹修改go执行文件名字,防止和本来的arm架构的go重名,并且提醒自己使用的go环境
cd go_x86_1.19/bin
mv go gox86
配置环境
vim ~/.bash_profile

source ~/.bash_profile
测试
gox86 version

安装go-python3包
进入你的项目工程目录
export PKG_CONFIG_PATH=/Users/gxy/opt/anaconda3/envs/go_python/lib/pkgconfig
gox86 get github.com/datadog/go-python3
调用自定义python
目录结构

测试的python文件 hello.py:
a = 10
def SayHello(xixi):
return xixi + "haha"
go调用python的过程分为以下5步:
- 初始化python环境
- 引入模块py对象
- 使用该模块的变量与函数
- 解析结果
- 销毁python3运行环境
main.go:
package main
import (
"fmt"
"os"
"github.com/datadog/go-python3"
)
func init() {
// 1. 初始化python环境
python3.Py_Initialize()
if !python3.Py_IsInitialized() {
fmt.Println("Error initializing the python interpreter")
os.Exit(1)
}
}
func main() {
// 2. 设置本地python import 的路径
p := "/Users/gxy/opt/anaconda3/envs/go_python/lib/python3.7/site-packages"
InsertBeforeSysPath(p)
// 3. 导入hello模块
hello := ImportModule("./hello", "hello")
// pyObject => string 解析结果
helloRepr, err := pythonRepr(hello)
if err != nil {
panic(err)
}
fmt.Printf("[MODULE] repr(hello) = %s\n", helloRepr)
// 4. 获取变量
a := hello.GetAttrString("a")
aString, err := pythonRepr(a)
if err != nil {
panic(err)
}
fmt.Printf("[VARS] a = %#v\n", aString)
// 5. 获取函数方法
SayHello := hello.GetAttrString("SayHello")
// 设置调用的参数(一个元组)
args := python3.PyTuple_New(1) // 创建存储空间
python3.PyTuple_SetItem(args, 0, python3.PyUnicode_FromString("gxy")) // 设置值
res := SayHello.Call(args, python3.Py_None) // 调用
fmt.Printf("[FUNC] res = %s\n", python3.PyUnicode_AsUTF8(res))
// 6. 调用第三方库sklearn
sklearn := hello.GetAttrString("sklearn")
skVersion := sklearn.GetAttrString("__version__")
sklearnRepr, err := pythonRepr(sklearn)
if err != nil {
panic(err)
}
skVersionRepr, err := pythonRepr(skVersion)
if err != nil {
panic(err)
}
fmt.Printf("[IMPORT] sklearn = %s\n", sklearnRepr)
fmt.Printf


1269

被折叠的 条评论
为什么被折叠?



