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

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

How to capture the output of the terminal using Go?

问题

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

echo "john" | goprogram

输出是 hi john

当使用cat命令时

cat list_name.txt | goprogram

输出为

  1. hi doe
  2. hi james
  3. 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

  1. hi doe
  2. hi james
  3. hi chris

Is there a way to do this using Go?

答案1

得分: 1

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

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. func main() {
  9. s := bufio.NewScanner(os.Stdin)
  10. for s.Scan() {
  11. fmt.Println("hi", s.Text())
  12. }
  13. if s.Err() != nil {
  14. log.Fatal(s.Err())
  15. }
  16. }

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

英文:

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

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. func main() {
  9. s := bufio.NewScanner(os.Stdin)
  10. for s.Scan() {
  11. fmt.Println("hi", s.Text())
  12. }
  13. if s.Err() != nil {
  14. log.Fatal(s.Err())
  15. }
  16. }

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:

确定