Golang calling Python

Source: Internet
Author: User
Tags rounds python script
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: Make sure Python is properly installed, so-called correct installation, is to find libpython.so (dylib) in the system, find Python.h. General Linux Direct installation Python-devel,mac can be installed directly with homebrew.

Golang installation: Golang do not need any special processing, can find 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.

Gogetgithub.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

Importnumpyimportsklearna =10DEFB (Xixi): Returnxixi + "haha"

Then write a go script:

Packagemainimport ("Github.com/sbinet/go-python" "FMT") Funcinit () {    ERR: = Python. Initialize () Iferr! = Nil {        Panic (err. Error ())    }}var pystr = python. Pystring_fromstringvar gostr = python. Pystring_as_stringfuncmain () {//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 Pyth Onimportpathfunc Insertbeforesyspath (P string) string {    sysmodule: = Python. Pyimport_importmodule ("sys")     Path: = sysmodule.getattrstring ("path")     python. Pylist_insert (path, 0, PYSTR (p)) returngostr (path. Repr ())}//Importmodule Willimportpython 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) = a=10b= &python. Pyobject{ptr: (*python._ctype_struct__object) (0XE90B1B8)}b (' xixi ') = Xixihahasklearn = Sklearn Version = ' 0.18.1 '

Here's a quick explanation. The path to this script is first added to the Sys.path. Then call Pyimport_importmodule to import the package

Using getattrstring, you can get the properties of an object based on the property name, which is equivalent to a. Operation in Python. The Python function can be called with the Object.call method, and the list parameters are constructed using tuple. The return value is converted from a Python string to a C or go string using pystring_as_string.

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.