How can Go call methods in Python?
In Golang, you can call a Python method by using the os/exec package to execute a Python script and capture its output.
Here is an example code that demonstrates how to call a Python method in Golang.
package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
// 定义要执行的Python脚本和参数
pythonScript := "path/to/python/script.py"
scriptArgs := []string{"arg1", "arg2"}
// 创建一个Cmd对象,用于执行Python脚本
cmd := exec.Command("python", append([]string{pythonScript}, scriptArgs...)...)
// 执行Python脚本并捕获输出结果
output, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
// 输出Python脚本的结果
fmt.Println(string(output))
}
The code snippet above starts by defining the path and arguments for the Python script to be executed. Using the exec.Command function, a Cmd object is created specifying the command to run as python, with the script’s path and arguments. It then executes the Python script using the cmd.Output method to capture the output. Finally, the output is converted to a string and displayed.
Please make sure that you have properly installed and configured the Python environment before running this code.