Golang – 无法从已管道化的 Windows 命令获取结果

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

Golang - Unable to get results from pipped Windows command

问题

我正在努力获取一个包含管道的Windows命令的输出。以下是该命令:

systeminfo | findstr /B /C:"OS Name"

以下是代码:

c1 := exec.Command("systeminfo")
c2 := exec.Command("findstr", "/B", `/C:"OS Name"`)

r, w := io.Pipe()
c1.Stdout = w
c2.Stdin = r

var b2 bytes.Buffer
c2.Stdout = &b2

c1.Start()
c2.Start()
c1.Wait()
w.Close()
c2.Wait()
io.Copy(os.Stdout, &b2)
fmt.Println(b2)

输出:[]

如果我在命令提示符中复制/粘贴该命令,它将返回结果。不确定为什么无法在我的Go程序中反映出来。我尝试了几种变体,包括在第一个命令中添加"cmd"、"/C",但都没有成功。

英文:

I am struggling to get the output for a Windows command that has a pipe in it. Here is the command:

> systeminfo | findstr /B /C:"OS Name"

Here is the code:

c1 := exec.Command("systeminfo")
c2 := exec.Command("findstr", "/B", `/C:"OS Name"`)

r, w := io.Pipe()
c1.Stdout = w
c2.Stdin = r

var b2 bytes.Buffer
c2.Stdout = &b2

c1.Start()
c2.Start()
c1.Wait()
w.Close()
c2.Wait()
io.Copy(os.Stdout, &b2)
fmt.Println(b2)

> Output: []

If I copy/paste the command in cmd, it will return results. Not sure why I can't get that reflected in my Go programme. I tried several variants, including the addition of "cmd", "/C" in the first command but no success either.

答案1

得分: 1

移除io.Copy以不重定向到STDOUT,并打印缓冲区的内容。

	systemCmd := exec.Command("systeminfo")
	findCmd := exec.Command("findstr", "/B", "/C:OS Name")

	reader, writer := io.Pipe()
	buf := bytes.NewBuffer(nil)
	systemCmd.Stdout = writer
	findCmd.Stdin = reader
	findCmd.Stdout = buf
	systemCmd.Start()
	findCmd.Start()
	systemCmd.Wait()
	writer.Close()
	findCmd.Wait()
	reader.Close()

	fmt.Println(">>" + buf.String())

例如:

PS C:\Users\user\Documents> go run .\main.go
>>OS Name:                   Microsoft Windows 10 Pro
英文:

Remove the io.Copy to no redirect to STDOUT and print the content of the buffer.

	systemCmd := exec.Command("systeminfo")
	findCmd := exec.Command("findstr", "/B", "/C:OS Name")

	reader, writer := io.Pipe()
	buf := bytes.NewBuffer(nil)
	systemCmd.Stdout = writer
	findCmd.Stdin = reader
	findCmd.Stdout = buf
	systemCmd.Start()
	findCmd.Start()
	systemCmd.Wait()
	writer.Close()
	findCmd.Wait()
	reader.Close()

	fmt.Println(">>" + buf.String())

ie:

PS C:\Users\user\Documents> go run .\main.go
>>OS Name:                   Microsoft Windows 10 Pro

huangapple
  • 本文由 发表于 2022年7月7日 01:04:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/72887417.html
匿名

发表评论

匿名网友

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

确定