run a python script in go

You can run a Python script in Go by using the os/exec package to execute the Python interpreter with your script as an argument. Here is an example code:

main.go
package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "os/exec"
)

func main() {
    // Read the Python script from file
    script, err := ioutil.ReadFile("path/to/your/script.py")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    // Execute the Python script
    cmd := exec.Command("python", "-c", string(script))
    output, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    // Print the output
    fmt.Println(string(output))
}
519 chars
29 lines

In this example, we first read the Python script from file using the ioutil package. Then, we create a exec.Cmd object with the Python interpreter as the command and the script as an argument. We execute the command and capture the output using the CombinedOutput() function. Finally, we print the output to the console.

gistlibby LogSnag