【问题标题】:How to capture the output of the terminal using Go?如何使用 Go 捕获终端的输出?
【发布时间】:2021-09-13 13:21:53
【问题描述】:

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

echo "john" | goprogram

输出为hi john

使用命令cat

cat list_name.txt | goprogram

输出使用

hi doe
hi james
hi chris

有没有办法使用 Go 来做到这一点?

【问题讨论】:

标签: go


【解决方案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。对于标准输入中的每一行,程序都会打印“hi”和该行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 2013-03-22
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    相关资源
    最近更新 更多