Golang调用Python
https://yq.aliyun.com/articles/117329
Python是时髦的机器学习御用开发语言,Golang是大红大紫的新时代后端开发语言。Python很适合让搞算法的写写模型,而Golang很适合提供API服务,两位同志都红的发紫,这里就介绍一下正确搅基的办法
原理
Python提供了丰富的C-API。而C和Go又可以通过cgo无缝集成。所以,直接通过Golang调用libpython,就可以实现Go调Python的功能了。确实没啥神奇,只要会用C调Python,马上就知道怎么用了。但问题是,如果有的选择,这个年代还有多少人愿意去裸写C和C++呢?诚心默念Golang大法好。
准备工作
- Python :确保Python正确安装,所谓正确安装,就是在系统中能找到
libpython.so(dylib)
,找到Python.h
。一般linux直接安装python-devel
,mac直接用homebrew安装就可以。 - Golang安装:Golang不需要什么特殊的处理,能找到
go
即可。
安装libpython-go-binding
虽然直接用cgo调用libpython也不是不可以,但是有native-binding用起来肯定要爽的多。Github上有一个现成的Binding库go-python。
go get github.com/sbinet/go-python
如果Python安装正确,这里会自动编译并显示提示,事就这样成了。
Have a try
首先写一个测试Python脚本
import numpy
import sklearn
a = 10
def b(xixi):
return xixi + "haha"
然后写一个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
var GoStr = python.PyString_AS_STRING
func main() {
// import hello
InsertBeforeSysPath("/Users/vonng/anaconda2/lib/python2.7/site-packages")
hello := ImportModule("/Users/vonng/Dev/go/src/gitlab.alibaba-inc.com/cplus", "hello")
fmt.Printf("[MODULE] repr(hello) = %s\n", GoStr(hello.Repr()))
// print(hello.a)
a := hello.GetAttrString("a")
fmt.Printf("[VARS] a = %#v\n", python.PyInt_AsLong(a))
// print(hello.b)
b := hello.GetAttrString("b")
fmt.Printf("[FUNC] b = %#v\n", b)
// args = tuple("xixi",)
bArgs := python.PyTuple_New(1)
python.PyTuple_SetItem(bArgs, 0, PyStr("xixi"))
// b(*args)
res := b.Call(bArgs, python.Py_None)
fmt.Printf("[CALL] b('xixi') = %s\n", GoStr(res))
// sklearn
sklearn := hello.GetAttrString("sklearn")
skVersion := sklearn.GetAttrString("__version__")
fmt.Printf("[IMPORT] sklearn = %s\n", GoStr(sklearn.Repr()))
fmt.Printf("[IMPORT] sklearn version = %s\n", GoStr(skVersion.Repr()))
}
// InsertBeforeSysPath will add given dir to python import path
func InsertBeforeSysPath(p string) string {
sysModule := python.PyImport_ImportModule("sys")
path := sysModule.GetAttrString("path")
python.PyList_Insert(path, 0, PyStr(p))
return GoStr(path.Repr())
}
// 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)
return python.PyImport_ImportModule(name) // return __import__(name)
}
打印输出为:
repr(hello) = <module 'hello' from '/Users/vonng/Dev/go/src/gitlab.alibaba-inc.com/cplus/hello.pyc'>
a = 10
b = &python.PyObject{ptr:(*python._Ctype_struct__object)(0xe90b1b8)}
b('xixi') = xixihaha
sklearn = <module 'sklearn' from '/Users/vonng/anaconda2/lib/python2.7/site-packages/sklearn/__init__.pyc'>
sklearn version = '0.18.1'
这里简单解释一下。首先将这个脚本的路径添加到sys.path
中。然后调用PyImport_ImportModule
导入包
使用GetAttrString
可以根据属性名获取对象的属性,相当于python中的.
操作。调用Python函数可以采用Object.Call
方法,,列表参数使用Tuple来构建。返回值用PyString_AS_STRING
从Python字符串转换为C或Go的字符串。
更多用法可以参考Python-C API文档。
但是只要有这几个API,就足够 Make python module rock & roll。充分利用Golang和Python各自的特性,构建灵活而强大的应用了。
Golang调用Python的更多相关文章
- Golang 调用 Python 代码
go 中的 cgo 模块可以让 go 无缝调用 c 或者 c++ 的代码,而 python 本身就是个 c 库,自然也可以由 cgo 直接调用,前提是指定正确的编译条件,如 Python.h 头文件( ...
- golang和python互相调用
http://blog.yuanzhaoyi.cn/2018/06/27/golang_python.html python3-ctypes: https://docs.python.org/3.5/ ...
- DES对称加密算法实现:Java,C#,Golang,Python
数据加密标准(DES,Data Encryption Standard,简写DES)是一种采用块密码加密的对称密钥算法,加密分组长度为64位,其中8.16.24.32.40.48.56.64 等8位是 ...
- cpp 调用python
在用cpp调用python时, 出现致命错误: no module named site , 原因解释器在搜索路径下没有找到python库.可以在调用Py_Initialize前,调用 Py_Se ...
- c调用python
#include <Python.h>//python33(python2.x有几个函数不对应) /* PyImport_ImportModule 导入一个Python模块并返回它的指针 ...
- golang调用c++的dll库文件
最近使用golang调用c++的dll库文件,简单了解了一下,特作此笔记:一.DLL 的编制与具体的编程语言及编译器无关 dll分com的dll和动态dll,Com组件dll:不管是何种语言写的都可以 ...
- linux+php+apache web调用python脚本权限问题解决方案
lamp : linux + apache + mysql + php 在上篇随笔中linux+php+apache调用python脚本时出现的问题的根本原因是:apache运行时使用的apache用 ...
- linux+php+apache web调用python脚本权限问题
lamp : linux + apache + mysql + php 在近期项目中使用 linux + apache + php调用python脚本是出现以下权限问题: build/bdist.li ...
- C#中调用python方法
最近因为项目设计,有部分使用Python脚本,因此代码中需要调用python方法. 1.首先,在c#中调用python必须安装IronPython,在 http://ironpython.codepl ...
随机推荐
- Physically Based Shader Development for Unity 2017 Develop Custom Lighting Systems (Claudia Doppioslash 著)
http://www.doppioslash.com/ https://github.com/Apress/physically-based-shader-dev-for-unity-2017 Par ...
- 【ECharts】1.学习ECharts从现在开始:第一个Echart图形
首先,你需要下载ECharts所需的文件,我使用的是echarts-2.0.2版本,点击这里下载:echarts-2.0.2 下载解压后,下面有一系列文件夹,其中build中有我们需要引入的JS文件, ...
- es6中reduce()方法和reduceRight()方法
es6中reduce()方法从左往右开始 参数:prev:它是上一次调用回调时返回的结果,每次调用的结果都会给prev cur:当前的元素 index:当前的索引 arr:循环的数组 返回值:函数累计 ...
- centos 启动一个tcp服务程序
需要先yum安装: yum install nc 启动服务: nc -l 80
- redis命令之 ----SortedSed(有序集合)
ZADD ZADD key score member [[score member] [score member] ...] 将一个或多个 member 元素及其 score 值加入到有序集 key ...
- Zookeeper 到底能帮我们解决哪些问题?
Zookeeper 从设计模式角度来看,是一个基于观察者模式设计的分布式服务管理框架,它负责存储和管理大家都关心的数据,然后接受观察者的注册,一旦这些数据的状态发生变化,Zookeeper 就将负责通 ...
- Vue 结合 SignalR 实现前后端实时消息同步
最近业务中需要实现服务器端与客户端的实时通信功能,对Signalr做了一点总结和整理. SignalR 作为 ASP.NET 的一个库,能够简单方便地为应用提供实时的服务器端与客户端双向通信功能. ...
- A Pattern Language for Parallel Programming
The pattern language is organized into four design spaces. Generally one starts at the top in the F ...
- 【JS】---5 JS通过事件隐藏显示元素
JS通过事件隐藏显示元素 在开发中,很多时候我们需要点击事件,才显示隐藏元素.那如何做到页面刚开始就把标签隐藏. 有两种方法: (1) display:none <div id=" ...
- Binding ,抄自 http://www.cnblogs.com/cnblogsfans/archive/2011/02/19/1958586.html
1. 绑定到其它元素 <Grid> <StackPanel > <TextBox x:Name="textBox1" Height="150 ...