This is a creation in Article, where the information may have evolved or changed.
To read the original, click
Summary: Python is a trendy machine learning Queen development language, Golang is a new era backend development language for rounds. Python is a great fit for algorithmic writing, and Golang is perfect for providing API services, and the two comrades are red purple, and here's a good way to get the right mix of bases. [Do him a gun. jpg] (http://ata2-img.cn-hangzhou.img-pub.aliyun-inc.com/f5ad9d2dbd36c37ef742c7be6998
Python is a trendy machine learning Queen development language, Golang is a new era backend development language for rounds. Python is a great fit for algorithmic writing, and Golang is well suited to providing API services, and the two comrades are red-purple, and here's a good way to get the right mix of bases.
Principle
Python offers a wealth of c-api. and C and go can be seamlessly integrated via CGO. So, by calling Libpython directly from Golang, you can implement the function of Go-tune python. There is no magic, as long as the C-tone python, immediately know how to use. But the question is, if there is a choice, how many people in this age are willing to write C and C + + naked? Sincerity Meditation Golang Dafa good.
Preparatory work
- python: Ensure that Python is properly installed, so-called correct installation, is in the system can find
libpython.so (dylib) , find python.h . General Linux Direct installation python-devel , Mac can be installed directly with homebrew.
- Golang installation: Golang do not need any special treatment, can be found
go .
Installing libpython-go-binding
Although it is not possible to call Libpython directly with CGO, there is definitely much more to native-binding use. There is a ready-made binding library Go-python on GitHub.
goget github.com/sbinet/go-python
If Python is installed correctly, this will automatically compile and display a hint, and that's it.
Have a try
First write a Test Python script
import numpyimport Sklearna = 10 def b (Xixi) : return Xixi + " haha "
Then write a go script:
PackageMainImport("Github.com/sbinet/go-python" "FMT")func init() {err: = python. Initialize ()ifErr! = Nil {panic (err. Error ())}}var pystr = python. Pystring_fromstringvar gostr = python. Pystring_as_stringfunc main() {//import HelloInsertbeforesyspath ("/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 would add given dir to PythonImportPathfunc Insertbeforesyspath (P string) string {sysmodule: = python. Pyimport_importmodule ("SYS") Path: = Sysmodule.getattrstring ("Path") python. Pylist_insert (path, 0, PYSTR (p))returnGostr (path. Repr ())}//Importmodule wouldImportPython module from given Directoryfunc importmodule (dir, name string) *python. Pyobject {sysmodule: = python. Pyimport_importmodule ("SYS") //ImportSYS path: = sysmodule.getattrstring ("Path")//Path = Sys.path python. Pylist_insert (path, 0, Pystr (dir))//Path.insert (0, dir)returnPython. Pyimport_importmodule (name)//return__IMPORT__ (name)}
Print output as:
repr(hello) = <module' Hello 'From'/users/vonng/dev/go/src/gitlab.alibaba-inc.com/cplus/hello.pyc '>a=Tenb= &python. Pyobject{ptr: (*python._ctype_struct__object) (0XE90B1B8)} b(' Xixi ') = Xixihahasklearn = <module' Sklearn 'From'/users/vonng/anaconda2/lib/python2.7/site-packages/sklearn/__init__.pyc '>sklearn Version =' 0.18.1 '
Here's a quick explanation. First, add the path to the script sys.path . Then call the PyImport_ImportModule import package
UseGetAttrStringYou can get the properties of an object based on the property name, which is equivalent to Python.Operation. Calling a Python function can takeObject.Callmethod, the list parameter is constructed using tuple. return value withPyString_AS_STRINGA string converted from a Python string to a C or go.
For more usage, refer to the PYTHON-C API documentation.
But with these APIs, it's enough to make the Python module rock & Roll. Take advantage of Golang and Python's respective features to build flexible and powerful applications.
To read the original, click