如何使用Go捕获终端的输出?

huangapple go评论70阅读模式
英文:

How to capture the output of the terminal using Go?

问题

我想使用Go创建一个简单的程序,可以在终端输出中获取输出。例如:

echo "john" | goprogram

输出是 hi john

当使用cat命令时

cat list_name.txt | goprogram

输出为

hi doe
hi james
hi chris

有没有办法使用Go实现这个功能?

英文:

I want to create a simple program using Go that can get an output in the terminal output. For example:

echo "john" | goprogram

The output is hi john

When using command cat

cat list_name.txt | goprogram

The output using

hi doe
hi james
hi chris

Is there a way to do this using Go?

答案1

得分: 1

os.Stdin 中读取。这是一个实现 Hi 程序的示例代码。

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

func main() {
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		fmt.Println("hi", s.Text())
	}
	if s.Err() != nil {
		log.Fatal(s.Err())
	}
}

该程序创建了一个 scanner 来逐行读取 os.Stdin。对于 stdin 中的每一行,程序会打印 "hi" 和该行内容。

英文:

Read from os.Stdin. Here's an example implementation of the Hi program.

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

func main() {
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		fmt.Println("hi", s.Text())
	}
	if s.Err() != nil {
		log.Fatal(s.Err())
	}
}

This program creates a scanner to read os.Stdin by line. For each line in stdin, the program prints "hi" and the line.

huangapple
  • 本文由 发表于 2021年9月13日 11:00:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/69156797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定