Running Python code from a Go application can be highly useful for integrating Python libraries or leveraging existing Python scripts. In this article, we'll explore how to execute Python code from within Go using a couple of methods that involve both basic shell command execution and leveraging the cffi or gopy tools.
Method 1: Using os/exec package
The simplest way to run Python code from Go is by calling a Python script directly using Go’s built-in os/exec package. This method is straightforward and works well if you're dealing with a standalone Python script.
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("python3", "-c", "print('Hello from Python!')")
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("Error executing Python code:", err)
return
}
fmt.Print(string(out))
}
In the example above, we create and run a Go command that executes Python code directly.
Method 2: Using cgo
If you need deeper integration, such as passing data between Go and Python, cgo allows Go packages to call C code directly. You can compile Python as an embeddable binary or make use of CFFI to setup wrappers. However, this involves more setup.
Here, we assume that you’ve properly set up a Python C extension.
// #include <Python.h>
import "C"
func main() {
C.Py_Initialize()
defer C.Py_Finalize()
pCode := C.CString("import sys; print('Hello from Python')")
C.PyRun_SimpleString(pCode)
C.free(unsafe.Pointer(pCode))
}
This code initializes the Python interpreter, runs a simple Python command, and then finalizes the interpreter. Make sure you have a Python development environment set up and linked properly to allow the Go program to include Python.h.
Method 3: Using gopy
Gopy is a tool that helps in generating Go packages that call into your Python code. It enables the exporting of functions from Python to be used in Go.
# mymodule.py
def add(a, b):
return a + b
This Python module can then be used in Go like this:
package main
import (
"fmt"
"examples/mymodule"
)
func main() {
result := mymodule.Add(3, 4)
fmt.Println("Result from Python module:", result)
}
In this setup, you'll need to generate the Go bindings using the gopy tool and then build your project, allowing seamless interaction with Python functions from your Go application.
Conclusion
Integrating Python with Go opens up a wide variety of functionalities which might be desired when leveraging the best of both languages. Each of these methods has trade-offs on performance and ease of use, so choose the one that best fits your scenario.