douchi5822 2014-02-12 20:16
浏览 54
已采纳

如何将缓冲区打印到通过寻呼机通过管道输出的stdout?

I have a large buffer (buffer []byte) that I would like to print to stdout but pipe through a pager like less or more. Kind of like the man command. I don't want to write the buffer to tmp file first or make the user manually pipe the output to a pager on the command line.

I can find examples of how to pipe the output of one command to another, but nothing starting with an internal buffer.

Any ideas? Thanks.

  • 写回答

2条回答 默认 最新

  • douzhi1919 2014-02-12 20:50
    关注

    In order to pipe to a pager, you can do something like this:

    package main
    
    import (
            "fmt"
            "io"
            "os"
            "os/exec"
    )
    
    func main() {
            // declare your pager
            cmd := exec.Command("less")
            // create a pipe (blocking)
            r, stdin := io.Pipe()
            // Set your i/o's
            cmd.Stdin = r
            cmd.Stdout = os.Stdout
            cmd.Stderr = os.Stderr
    
            // Create a blocking chan, Run the pager and unblock once it is finished
            c := make(chan struct{})
            go func() {
                    defer close(c)
                    cmd.Run()
            }()
    
            // Pass anything to your pipe
            fmt.Fprintf(stdin, "hello world
    ")
    
            // Close stdin (result in pager to exit)
            stdin.Close()
    
            // Wait for the pager to be finished
            <-c
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上