Fork of https://github.com/tliron/py4go/
|
|
5 anni fa | |
|---|---|---|
| examples | 5 anni fa | |
| scripts | 5 anni fa | |
| .gitignore | 5 anni fa | |
| LICENSE | 5 anni fa | |
| NOTICE | 5 anni fa | |
| README.md | 5 anni fa | |
| common.go | 5 anni fa | |
| concurrency.go | 5 anni fa | |
| exception.go | 5 anni fa | |
| general.go | 5 anni fa | |
| go.mod | 5 anni fa | |
| go.sum | 5 anni fa | |
| import.go | 5 anni fa | |
| module.go | 5 anni fa | |
| object.go | 5 anni fa | |
| path.go | 5 anni fa | |
| primitive.go | 5 anni fa | |
| reference.go | 5 anni fa | |
| type.go | 5 anni fa |
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())
}
See the examples directory for more detail.
Generally speaking, calling Python code is easy but calling Go code from Python requires a lot more work, including writing embedded wrapper functions in C. Perhaps in the future we will be able to automate this.
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/or
python.EnsureGilState as appropriate. See the examples for more detail.