在Python中调用Golang的方法,可以使用subprocess
模块来启动一个Golang的可执行文件,并通过标准输入输出进行数据传递。
以下是一个示例:
- 创建一个Golang的可执行文件(例如
main.go
):
package main
import "fmt"
func main() {
var input string
fmt.Scanln(&input)
fmt.Println("Golang received:", input)
}
- 编译Golang代码,生成可执行文件:
go build main.go
- 在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等。具体方法选择取决于你的需求和情况。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/841232.html