Go 的分页输出

Top*_*opo 1 stdout go pager

我正在尝试使用$PAGER或手动调用从 golang 打印到标准输出,more或者less允许用户轻松滚动浏览许多选项。我怎样才能做到这一点?

Mar*_*all 5

您可以使用os/exec包启动一个运行的进程less(或任何在 中的进程$PAGER),然后将一个字符串通过管道传输到其标准输入。以下对我有用:

func main() {
    // Could read $PAGER rather than hardcoding the path.
    cmd := exec.Command("/usr/bin/less")

    // Feed it with the string you want to display.
    cmd.Stdin = strings.NewReader("The text you want to show.")

    // This is crucial - otherwise it will write to a null device.
    cmd.Stdout = os.Stdout

    // Fork off a process and wait for it to terminate.
    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}
Run Code Online (Sandbox Code Playgroud)