英文:
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
}
如果我漏掉了什么,请告诉我。我很乐意帮助你。
英文:
I edited your code and it seems working now check it out.
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
}
if I miss something please let me know. I would like to help.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论