如何在Go中重定向命令,而不将结果输出到终端?

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

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 -lls -l | grep "py"之类的命令。但pbcopy命令不会显示输入,只会将输入保存到剪贴板中。

那么,我该如何在Go的os/exec包中使用重定向(或管道)来使用pbcopy命令呢?

英文:

I want to run a command: pbcopy &lt; file.csv within my Go program. However, it looks like Go's os/exec package cannot redirect one command to another using &lt; syntax. So I decided to use pipe in my program. However, this script:

package main

import (
	&quot;os/exec&quot;
)

func main() {
	cmd1 := exec.Command(&quot;cat&quot;, &quot;test.csv&quot;)
	cmd2 := exec.Command(&quot;pbcopy&quot;)
	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 &quot;py&quot; 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(&quot;test.csv&quot;) and pass the file pointer directly to cmd2.Stdin.

huangapple
  • 本文由 发表于 2014年4月28日 12:12:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/23332384.html
匿名

发表评论

匿名网友

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

确定