Fork of https://github.com/tliron/py4go/
|
|
5 jaren geleden | |
|---|---|---|
| examples | 5 jaren geleden | |
| scripts | 5 jaren geleden | |
| .gitignore | 5 jaren geleden | |
| .pydevproject | 5 jaren geleden | |
| LICENSE | 5 jaren geleden | |
| NOTICE | 5 jaren geleden | |
| README.md | 5 jaren geleden | |
| common.go | 5 jaren geleden | |
| concurrency.go | 5 jaren geleden | |
| exception.go | 5 jaren geleden | |
| general.go | 5 jaren geleden | |
| go.mod | 5 jaren geleden | |
| go.sum | 5 jaren geleden | |
| import.go | 5 jaren geleden | |
| module.go | 5 jaren geleden | |
| object.go | 5 jaren geleden | |
| path.go | 5 jaren geleden | |
| primitive.go | 5 jaren geleden | |
| reference.go | 5 jaren geleden | |
| type.go | 5 jaren geleden |
Execute Python 3 code from within your Go program.
With py4go you can also expose Go functions to be called from that Python code.
package main
import (
"fmt"
"github.com/tliron/py4go"
)
func main() {
// Initialize Python
python.Initialize()
defer python.Finalize()
// Import Python code (foo.py)
foo, _ := python.Import("foo")
defer foo.Release()
// Get access to a Python function
hello, _ := foo.GetAttr("hello")
defer hello.Release()
// Call the function with arguments
r, _ := hello.Call("myargument")
defer r.Release()
fmt.Printf("Returned: %s\n", r.String())
// Expose a Go function to Python via a C wrapper
// (Just use "import api" from Python)
api, _ := python.CreateModule("api")
defer api.Release()
api.AddModuleCFunctionNoArgs("my_function", C.api_my_function)
api.EnableModule()
}
Calling Python code from Go is easy because Python is a dynamic language and CPython is an interpreted runtime. Exposing Go code to Python is more involved as it requires writing wrapper functions in C, which we omitted in the example above. See the examples directory for more detail.
This is not an implementation of Python in Go. Rather, py4go works by embedding CPython into your Go program using cgo functionality. The advantage of this approach is that you are using the standard Python runtime and can thus make use of the entire ecosystem of Python libraries, including wrappers for C libraries. But there are several issues to be aware of:
pkg-config: python3-embed to
locate the CPython SDK, which works on Fedora-based operating systems. But, because where you
build will determine the requirements for where you will run, it may be best to build on
Fedora, either directly or in a virtual machine or container. Unfortunately cgo does not let us
parameterize that pkg-config directive, thus you will have to modify our source files in order to
build on/for other operating systems.Release on all Python references to ensure that they are
garbage collected. Luckily, the defer keyword makes this easy enough in many circumstances.python.SaveThreadState and
python.EnsureGilState as appropriate. See the examples for more detail.