Sling Academy
Home/Golang/How to run Python code with Go

How to run Python code with Go

Last updated: November 28, 2024

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.

Next Article: Working with generic structs in Go

Previous Article: How to handle network errors in Go: A deep dive

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant
  • Fixing Go error: syntax error: unexpected X, expecting Y