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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应