英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论