在Python里面调用Golang代码的方法
2025-09-01 14:35
Python
16
0
0
0
标题录入
封面图
在 Python 中调用 Go(Golang)代码,有几种常见的方法。下面我会详细说明每种方法的原理和实现方式,并给出示例。 --- ## ✅ 方法一:使用 `go` 命令运行 Go 程序(通过子进程) 这是最简单的方式,适用于你只需要运行一个 Go 程序并获取其输出。 ### 示例: 1. **Go 代码(hello.go)**: ```go package main import "fmt" func main() { fmt.Println("Hello from Go!") } ``` 2. **Python 调用 Go 程序**: ```python import subprocess # 编译 Go 程序(可选) subprocess.run(["go", "build", "-o", "hello", "hello.go"]) # 运行生成的二进制文件 result = subprocess.run(["./hello"], capture_output=True, text=True) print(result.stdout) # 输出: Hello from Go! ``` > ⚠️ 注意:需要确保系统中安装了 Go 并配置了环境变量。 --- ## ✅ 方法二:将 Go 编译为共享库(.so / .dll / .dylib),然后在 Python 中调用(使用 `ctypes` 或 `cffi`) 这种方法适合你希望在 Python 中直接调用 Go 函数,而不是运行整个程序。 ### 步骤: 1. **Go 代码(math.go)**: ```go package main import "C" //export Add func Add(a, b int) int { return a + b } func main() {} ``` 2. **编译为共享库**(Linux/macOS): ```bash go build -o libmath.so -buildmode=c-shared math.go ``` 3. **Python 调用共享库**: ```python import ctypes # 加载共享库 lib = ctypes.CDLL('./libmath.so') # 定义函数参数类型和返回类型 lib.Add.argtypes = [ctypes.c_int, ctypes.c_int] lib.Add.restype = ctypes.c_int # 调用 Go 函数 result = lib.Add(3, 4) print(result) # 输出: 7 ``` > ⚠️ Windows 上使用 `.dll`,macOS 使用 `.dylib`,注意路径问题。 --- ## ✅ 方法三:使用 `gRPC` 或 `HTTP API` 调用 Go 服务 如果你有一个独立的 Go 服务,可以通过网络接口与 Python 交互。 ### 示例(Go 服务): ```go package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello from Go!") } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) } ``` ### Python 调用: ```python import requests response = requests.get("http://localhost:8080") print(response.text) # 输出: Hello from Go! ``` --- ## ✅ 方法四:使用 `PyGo` 或 `GoPy`(第三方库) 有一些尝试将 Go 和 Python 混合使用的项目,但这些项目可能不稳定或不活跃。 - [PyGo](https://github.com/ysmood/pygo)(不推荐,已不再维护) - [GoPy](https://github.com/GoPy/GoPy)(也不太活跃) --- ## ✅ 总结对比 | 方法 | 是否需要编译 | 是否支持函数调用 | 适用场景 | |------|----------------|------------------|----------| | 子进程调用 | 否 | 否 | 简单执行 Go 程序 | | 共享库 + `ctypes` | 是 | 是 | 需要调用 Go 函数 | | gRPC / HTTP | 否 | 是 | 分布式服务、微服务 | | 第三方库 | 否 | 否 | 小众、不稳定 | --- ## ✅ 推荐方案 - 如果只是运行 Go 程序 → 使用 `subprocess` - 如果需要调用 Go 函数 → 使用 `go build -buildmode=c-shared` + `ctypes` - 如果构建微服务 → 使用 `gRPC` 或 `HTTP` --- 如需我帮你写具体的示例代码,可以告诉我你的具体需求(比如是调用某个函数还是运行程序)。
上一篇:
Python的gtts库将文字转为音频应该如何操作
下一篇:
Python怎么构建区块链
标题录入,一次不能超过6条
怎么分辨对方是朋友还是敌人
T:0.005788s,M:119.19 KB
返回顶部
留言
留言
评论