Files
gobridge/prefix_writer.go
what b4e77ce9a8 feat: 为 Python worker 输出添加行前缀,并启用无缓冲模式
- 新增 prefixWriter,对每行输出添加 [python:N] 前缀,便于与 Go 日志区分
- 注入 PYTHONUNBUFFERED=1,确保 print() 实时输出不被管道缓冲
2026-04-14 14:38:24 +08:00

53 lines
992 B
Go

package gobridge
import (
"bytes"
"io"
"sync"
)
// prefixWriter 对每一行输出添加固定前缀,线程安全。
type prefixWriter struct {
mu sync.Mutex
w io.Writer
prefix []byte
buf []byte
}
func newPrefixWriter(w io.Writer, prefix string) *prefixWriter {
return &prefixWriter{w: w, prefix: []byte(prefix)}
}
func (p *prefixWriter) Write(b []byte) (int, error) {
p.mu.Lock()
defer p.mu.Unlock()
n := len(b)
p.buf = append(p.buf, b...)
for {
idx := bytes.IndexByte(p.buf, '\n')
if idx < 0 {
break
}
line := append(p.prefix, p.buf[:idx+1]...)
if _, err := p.w.Write(line); err != nil {
return n, err
}
p.buf = p.buf[idx+1:]
}
return n, nil
}
// flush 将缓冲区中尚未以换行结尾的内容输出(进程退出时调用)。
func (p *prefixWriter) flush() {
p.mu.Lock()
defer p.mu.Unlock()
if len(p.buf) > 0 {
line := append(p.prefix, p.buf...)
line = append(line, '\n')
p.w.Write(line) //nolint
p.buf = nil
}
}