本文记录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")
__init__
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()

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

得善用API提供的Debug工具呀