温馨提示×

python调用golang的方法是什么

小亿
87
2024-01-27 15:02:53
栏目: 编程语言

在Python中调用Golang的方法,可以使用subprocess模块来启动一个Golang的可执行文件,并通过标准输入输出进行数据传递。

以下是一个示例:

  1. 创建一个Golang的可执行文件(例如main.go):
package main

import "fmt"

func main() {
    var input string
    fmt.Scanln(&input)
    fmt.Println("Golang received:", input)
}
  1. 编译Golang代码,生成可执行文件:
go build main.go
  1. 在Python中调用Golang的可执行文件:
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()

运行Python代码后,可以看到如下输出:

Python received: Golang received: Hello from Python

注意,这只是一种在Python中调用Golang方法的方法之一,还有其他的方法,如使用CGO、RPC等。具体方法选择取决于你的需求和情况。

0