英文:
How to redirect a command in Go without outputting the result to Terminal?
问题
我想在我的Go程序中运行一个命令:pbcopy < file.csv
。然而,看起来Go的os/exec
包无法使用<
语法将一个命令重定向到另一个命令。所以我决定在我的程序中使用管道。然而,当我运行以下脚本时:
package main
import (
"os/exec"
)
func main() {
cmd1 := exec.Command("cat", "test.csv")
cmd2 := exec.Command("pbcopy")
out, _ := cmd1.StdoutPipe()
cmd2.Stdin = out
cmd2.Run()
}
当我运行上述程序时,程序不会终止,看起来它在终端中等待用户输入。当我终止它并尝试粘贴结果到任何地方时,它不会接受输入并将其保存到剪贴板中。
然后,我将程序的最后一行从cmd2.Run()
更改为cmd2.Start()
,然后程序正常终止。然而,剪贴板中填充了一个空字符串,而不是将cat file.csv
的输出保存到剪贴板中。
我尝试寻找一些在Go的os/exec
中使用管道的示例,但我看到的所有示例都假设最终结果会输出到终端,例如ls -l | wc -l
或ls -l | grep "py"
之类的命令。但pbcopy
命令不会显示输入,只会将输入保存到剪贴板中。
那么,我该如何在Go的os/exec
包中使用重定向(或管道)来使用pbcopy
命令呢?
英文:
I want to run a command: pbcopy < file.csv
within my Go program. However, it looks like Go's os/exec
package cannot redirect one command to another using <
syntax. So I decided to use pipe in my program. However, this script:
package main
import (
"os/exec"
)
func main() {
cmd1 := exec.Command("cat", "test.csv")
cmd2 := exec.Command("pbcopy")
out, _ := cmd1.StdoutPipe()
cmd2.Stdin = out
cmd2.Run()
}
When I run the above program, the program doesn't terminate and it looks like waiting for the input from the user in Terminal. And when I terminate it and try to paste the result to anywhere it doesn't take the input and save it to the clipboard.
Then I change the last line of the program from cmd2.Run()
to cmd2.Start()
, then the program terminates properly. However, the clipboard is filled with an empty string and not saves the cat file.csv
output to clipboard.
I tried to look for some examples to use pipe in os.exec
in Go, but all of that I saw assume that the result is output to the Terminal in the end, such as ls -l | wc -l
or ls -l | grep "py"
or such things. But pbcopy
command doesn't display the input and just saves the input to clipboard.
So how can I use a redirect (or pipe) in os.exec
package in Go with pbcopy
command?
答案1
得分: 4
你需要启动命令1。命令2正在等待来自命令1的输入,并且可能会无限期等待。
cmd1.Start()
cmd2.Run()
**编辑:**回顾一下问题,为什么你要将其作为两个命令来执行呢?相反,你可以使用os.Open("test.csv")
直接将文件指针传递给cmd2.Stdin
。
英文:
You need to start command 1. Command 2 is waiting for input from command 1 and will likely wait indefinitely.
cmd1.Start()
cmd2.Run()
EDIT: looking back at the question, why are you doing this as two commands in the first place? Instead, you can os.Open("test.csv")
and pass the file pointer directly to cmd2.Stdin
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论