-
-
Save raychorn/4451ba6cb715ed4779739d2b250f39b1 to your computer and use it in GitHub Desktop.
A simple example to call python function from golang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, "" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment