Golang how would you pipe the stdout of a function to another function that executes fzf

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

Golang how would you pipe the stdout of a function to another function that executes fzf

问题

我们有一个如下所示的函数:

func example() {
   fmt.Println("January")
   fmt.Println("February")
   fmt.Println("March")
}

现在我们需要另一个函数,该函数将上述函数的输出传递给bash命令fzf,你会如何实现这个功能?

我知道我需要将stdout重定向到stdin,并且有一个完整的os.Pipe的概念。

所以我尝试先捕获stdout:

func capture(f func()) string {
  out := os.Stdout
  r, w, _ := os.Pipe()
  os.Stdout = w

  w.Close()
  os.Stdout = out

  var buf bytes.Buffer
  io.Copy(&buf, r)
  return buf.String()
}

这没有成功,我还没有弄清楚将stdout发送到执行fzf的函数的部分。

英文:

Say we have a the following function:

func example() {
   fmt.Println("January")
   fmt.Println("February")
   fmt.Println("March")
}

Now we need another function which takes the output of the above function to bash command fzf, how would you achieve this?

I know i have to redirect stdout to stdin, and there is a whole concept of os.Pipe

So i tried to capture the stdout first:

func capture(f func()) string {
  out := os.Stdout
  r, w, _ := os.Pipe()
  os.Stdout = w

  w.Close()
  os.Stdout = out

  var buf bytes.Buffer
  io.Copy(&buf, r)
  return buf.String()
}

Didn't work out and i haven't figured the part of sending stdout to the function that executes fzf

答案1

得分: 2

我编辑了你的代码,现在看起来可以工作了,请查看一下。

package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
)

func example() {
	fmt.Println("January")
	fmt.Println("February")
	fmt.Println("March")
}

func main() {
	str := capture(example)
	println("start", str, "end")

}

func capture(f func()) string {

	stdout := os.Stdout
	r, w, _ := os.Pipe()
	os.Stdout = w

	f()

	ChnOut := make(chan string)

	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		ChnOut <- buf.String()
	}()

	w.Close()
	os.Stdout = stdout
	str := <-ChnOut

	return str
}

如果我漏掉了什么,请告诉我。我很乐意帮助你。

英文:

PlayGround

I edited your code and it seems working now check it out.

package main

import (
	&quot;bytes&quot;
	&quot;fmt&quot;
	&quot;io&quot;
	&quot;os&quot;
)

func example() {
	fmt.Println(&quot;January&quot;)
	fmt.Println(&quot;February&quot;)
	fmt.Println(&quot;March&quot;)
}

func main() {
	str := capture(example)
	println(&quot;start&quot;, str, &quot;end&quot;)

}

func capture(f func()) string {

	stdout := os.Stdout
	r, w, _ := os.Pipe()
	os.Stdout = w

	f()

	ChnOut := make(chan string)

	go func() {
		var buf bytes.Buffer
		io.Copy(&amp;buf, r)
		ChnOut &lt;- buf.String()
	}()

	w.Close()
	os.Stdout = stdout
	str := &lt;-ChnOut

	return str
}

if I miss something please let me know. I would like to help.

huangapple
  • 本文由 发表于 2022年8月31日 19:12:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/73555006.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定