两个进程实时读写同一个文件

我有一个用例,其中一个运行 python 的进程将其执行日志写入一个文件。Goilang 中运行的另一个进程,想要实时读取文件的内容,例如日志流。但是为了读取文件的内容,似乎我必须等到 Python 进程完成。有没有办法让 python 进程正常终止,最后生成日志文件,并将日志流式传输到 golang 进程?

我的目的是让python进程日志流到golang进程。


心有法竹
浏览 116回答 1
1回答

万千封印

1. 简单的如果您使用的是 Linux,则将日志从 Python 写入标准输出并使用管道。来源.py | 目标(用go写的)package mainimport ("bufio""fmt""os")/* Three ways of taking input   1. fmt.Scanln(&input)   2. reader.ReadString()   3. scanner.Scan()   Here we recommend using bufio.NewScanner*/func main() {// To create dynamic arrayarr := make([]string, 0)scanner := bufio.NewScanner(os.Stdin)for {    fmt.Print("Enter Text: ")    // Scans a line from Stdin(Console)    scanner.Scan()    // Holds the string that scanned    text := scanner.Text()    if len(text) != 0 {        fmt.Println(text)        arr = append(arr, text)    } else {        break    }}// Use collected inputsfmt.Println(arr)}用法:echo "what a wanderful world" |./go-bin 另请阅读此Python redirect to StdOut2.权利。对于长时间运行的进程,使用命名管道可能更好。这是一个 linux 文件 (FIFO) GNU pipe。Python 写入此文件,Golang 读取 go 中的 FIFO 示例3. 可能矫枉过正。编写 Golang Web 服务器并从 python 调用服务器端点。如果可以更改 Python 源代码。此解决方案还应更加关注安全性。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go