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

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

王林
Release: 2024-02-06 08:18:04
forward
1001 people have browsed it

无法在 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())
Copy after login

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)
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template