【Python+C+Golang】在Go中使用go-python调用python模块--内部借助Python/C API 来调用Python

本文记录debug经验

API

PyObject* PyImport_ImportModule(const char *name)
//Return value: New reference.  返回__import__(name)

使用此API在Go中导入Python的模块。

Python代码如下:

hello.py:

import numpy
import sklearn

a=10

def b(xixi):
        return xixi+"haha"

print("calling python success")

将该文件放在helloworld文件夹下,在helloworld文件夹下再创建一个空文件__init__,于是hello可以作为模块被import。

Go代码如下:

package main

import(
    "github.com/sbinet/go-python"
    "fmt"
)

func init(){
    err :=python.Initialize()
    if err != nil{
        panic(err.Error())
    }
}
var PyStr = python.PyString_FromString

// ImportModule will import python module from given directory
func ImportModule(dir, name string) *python.PyObject {
    sysModule := python.PyImport_ImportModule("sys") // import sys
    path := sysModule.GetAttrString("path")                    // path = sys.path
    python.PyList_Insert(path, 0, PyStr(dir))                     // path.insert(0, dir)
    fmt.Println(path)
    return python.PyImport_ImportModule(name)            // return __import__(name)
}

func main(){
    hello:= ImportModule("/opt/py/helloworld","hello")   //注意包名hello和文件夹名字helloworld不能一样
    if hello == nil{
        python.PyErr_Print()
        fmt.Println("import module error")
    }
    fmt.Println(hello)
}

问题

总是返回空指针,表明没有import成功。
在这里插入图片描述

在确保路径都没错的情况下,调用python.PyErr_Print()发现了几个问题。
在这里插入图片描述
go-python包中的python是系统环境的python,要注意和自己的虚拟环境区分开。

可以在sys.path导入了系统python环境之后再insert虚拟环境中的site-packages,但有多个python环境时,导入一个包可能会导致版本冲突。

得善用API提供的Debug工具呀

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值