How can Python call a method in Golang?

In Python, you can call methods written in Golang by using the subprocess module to start a Golang executable and pass data through standard input and output.

Here is an example:

  1. The main file is named main.go.
package main

import "fmt"

func main() {
    var input string
    fmt.Scanln(&input)
    fmt.Println("Golang received:", input)
}
  1. Compile Golang code to generate an executable file.
go build main.go
  1. Invoke the executable file of Golang in Python.
import subprocess

# 启动Golang可执行文件
process = subprocess.Popen("./main", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

# 向Golang发送数据
input_data = "Hello from Python"
process.stdin.write(input_data.encode())
process.stdin.close()

# 读取Golang的输出
output_data = process.stdout.read().decode().strip()
print("Python received:", output_data)

# 等待Golang进程结束
process.wait()

After running the Python code, you will see the following output:

Python received: Golang received: Hello from Python

Please note that this is just one way to call Golang methods in Python, there are other methods such as using CGO, RPC, etc. The specific method chosen depends on your needs and circumstances.

bannerAds