英文:
Read from os.stdout
问题
我想将日志信息发送到一个套接字,为了实现这一目标,我需要首先捕获 os.stdout。我知道可以使用 os.pipe 重定向 os.stdout。但是是否有一种方法可以直接使用 bufio.NewReader 或 bufio.NewScanner 从 os.stdout 中读取?
func Start() {
//dataChan := make(chan string)
outC := make(chan string, 3)
defer close(outC)
conn, err := net.Dial("tcp", "localhost:9090")
if err != nil {
log.Fatal(err)
}
fmt.Println("first line!")
fmt.Println("second line!")
fmt.Println("third line!")
// write to channel
go func() {
scanner := bufio.NewScanner(os.Stdout)
for scanner.Scan() {
outC <- scanner.Text() + "\n"
err = scanner.Err()
if err != nil {
log.Fatal(err)
}
}
}()
// read from channel and print to connection
go func() {
out := <-outC
for {
conn.Write([]byte(out + "\n"))
}
}()
}
英文:
I would like to send log information to a socket, to achieve that, I need to first capture the os.stdout. I know i could redirect the os.stdout with os.pipe. But is there a way i directly read from os.stdout use bufio.NewReader or bufio.NewScanner?
func Start() {
//dataChan := make(chan string)
outC := make(chan string, 3)
defer close(outC)
conn, err := net.Dial("tcp", "localhost:9090")
if err != nil {
log.Fatal(err)
}
fmt.Println("first line!")
fmt.Println("second line!")
fmt.Println("third line!")
// write to channel
go func() {
scanner := bufio.NewScanner(os.Stdout)
for scanner.Scan() {
outC <- scanner.Text() + "\n"
err = scanner.Err()
if err != nil {
log.Fatal(err)
}
}
}()
// read from channel and print to connection
go func() {
out := <-outC
for {
conn.Write([]byte(out + "\n"))
}
}()
}
答案1
得分: 0
你可以通过os.Pipe来读取stdout。
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
go func() {
var buf bytes.Buffer
io.Copy(&buf, r)
outC <- buf.String()
}()
fmt.Println("第一行!")
fmt.Println("第二行!")
fmt.Println("第三行!")
w.Close()
os.Stdout = old // 恢复stdout
for {
select {
case out := <-outC:
conn.Write([]byte("读取 " + out + "\n"))
}
}
英文:
You could read stdout through os.Pipe
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
go func() {
var buf bytes.Buffer
io.Copy(&buf, r)
outC <- buf.String()
}()
fmt.Println("first line!")
fmt.Println("second line!")
fmt.Println("third line!")
w.Close()
os.Stdout = old // restore stdout
for {
select {
case out := <-outC:
conn.Write([]byte("read " + out + "\n"))
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论