Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

python 3.x - Python3 and subprocess.Popen, writing to stdin doesn't seem to work

I am trying to figure out how to start a subprocess with pipes on raspberry pi and feed it input on stdin and examine the output from stdout. I wrote a simple shell script to echo something so I could see if I could capture the output. the script loops until it sees an input that is only "q" then quits. I need to be able to send a single character, or a terminated string, several times during the run of the subprocess, and capture the output from the subprocess.

I see the first line of output on the stdout pipe, but then after a write to stdin, it hangs on the readline from stdout. This indicates to me, that the stdin write is not getting to the subprocess.

I have tried subprocess.communicate and several other more complicated suggestions but I have not been able to get any to send data to stdin on the subprocess. Below is the simple code I wrote to test this out so I could learn more about the subprocess module. Any assistance would be appreciated.

    # -------- simple bash script to echo stdin to stdout and terminate on "q" -------
    #!/bin/bash
    echo "Hello there"
    ans=""
    while ! [ "$ans" == "q" ]; do
      read ans
      echo "Input was $ans"
    done
    echo "all done"


    # --------- python test program ----------
    
    #!/usr/bin/env python3
    from subprocess import Popen, PIPE, STDOUT
    
    p = Popen(['./tst_read.sh'],  stdout=PIPE, stdin=PIPE, stderr=STDOUT)  
    print("Popen, pid:",p.pid) 
    print(p.stdout.readline().decode())
    p.stdin.write(b'some stuff
')
    print(p.stdout.readline().decode())
    p.stdin.write(b'more stuff
')
    print(p.stdout.readline().decode())
    p.stdin.write(b'q
')
    print(p.stdout.readline().decode())
    print("python finished")
    p.kill()

When I run the python program, I get this out and then the program waits forever for the next readline to return

    ~ $ ./test.py
    Popen, pid: 27283
    Hello there

I have to press ctrl/c to get control back to the keyboard. While the program appears to be hung, I checked that the subprocess is running (from another terminal window).

    ps -aux | grep 27283
    pi       27283  0.0  0.0   4608   596 pts/0    S+   10:15   0:00 /bin/bash ./tst_read.sh
question from:https://stackoverflow.com/questions/65848704/python3-and-subprocess-popen-writing-to-stdin-doesnt-seem-to-work

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...