Skip to content

Instantly share code, notes, and snippets.

@sysulq
Last active December 19, 2023 07:50
Show Gist options
  • Save sysulq/1a82ba31f0f1bec68d5d to your computer and use it in GitHub Desktop.
Save sysulq/1a82ba31f0f1bec68d5d to your computer and use it in GitHub Desktop.
A simple example to call python function from golang.
package main
import (
"github.com/qiniu/py"
"log"
//"path/filepath"
"strconv"
)
func callPythonFunction(file string, function string) (int, string) {
Module, err := py.Import(file)
if err != nil {
log.Print("py.Importg")
return 0, ""
}
Dict := Module.Dict()
if Dict == nil {
log.Print("Module.Dict")
return 0, ""
}
Func := Dict.GetItemString(function)
if Func == nil {
log.Print("Dict.GetItemString")
return 0, ""
}
Ret, err := Func.CallObject(nil)
if err != nil {
log.Print("Dict.CallObject")
return 0, ""
}
Tuple, ok := py.AsTuple(Ret)
if !ok {
log.Print("py.AsTuple")
return 0, ""
}
size := Tuple.Size()
if size == 2 {
value, err := Tuple.GetItem(0)
if err != nil {
log.Print("Tuple.GetItem")
return 0, ""
}
ok, _ := strconv.Atoi(value.String())
value, _ = Tuple.GetItem(1)
if err != nil {
log.Print("Tuple.GetItem")
return 0, ""
}
return ok, value.String()
} else {
log.Printf("Abnormal return values, number=%d", size)
}
return 0, ""
}
@austin-millan
Copy link

Is it possible to extend this to include arguments to the Python function? Otherwise this is really cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment