栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

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

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【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工具呀

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/907816.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号