Home >Backend Development >Golang >Can't read from Pipe using exec.Command in Go

Can't read from Pipe using exec.Command in Go

王林
王林forward
2024-02-06 08:18:041002browse

无法在 Go 中使用 exec.Command 从 Pipe 读取

Question content

I am writing a go program that sends data to another program via stdin and reads the response via stdout.

This is a script that acts as an "echo server" of sorts:

import sys

if __name__=='__main__':
    for line in sys.stdin:
        print("Hello", line.strip())

When I try to communicate with the program in Go, it hangs on buf.ReadLine(). This is my Go code:

package main

import (
    "bufio"
    "log"
    "os/exec"
)

func main() {
    cmd := exec.Command("python3", "app.py")
    stdout, _ := cmd.StdoutPipe()
    stdin, _ := cmd.StdinPipe()

    cmd.Start()

    stdin.Write([]byte("Bob\n"))

    buf := bufio.NewReader(stdout)
    buf.ReadLine()
    log.Println(buf)
}

Write() The function does not return an error. However, when I try ReadLine(), the program hangs. What did i do wrong?


Correct answer


This is not a problem with the Go code; your Python program is buffering output because its stdout is a pipe and not a terminal, so there is nothing wrong with Go readable, and you'll get a deadlock, with both processes waiting for input, and neither process producing any output.

See How to Flush the Print Function or Disable Output Buffering for ways to handle it in Python - the first applies to a single print statement, the second to the entire program . For your simple example they are all the same, but in other cases they may be different, so it's worth knowing the options.

The above is the detailed content of Can't read from Pipe using exec.Command in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete