Reputation: 855
I know that similar questions have been asked many times, but I didn't manage to apply those solutions to my case.
I have this interactive program:
#!/bin/sh
echo "banana"
while true
do
read line
echo $line
done
and I am trying to communicate with it via python, but this happens:
> python3
Python 3.3.1 (default, Apr 24 2013, 16:43:21)
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen,PIPE,STDOUT
>>> p = Popen("x.sh", stdin = PIPE, stdout = PIPE)
>>> print(p.stdout.readline())
b'banana\n'
>>> p.stdin.write(bytes('xyzgewgwer','UTF-8'))
10
>>> print(p.stdout.readline())
sometimes it hangs there, but sometimes it prints
b''
any idea?
Upvotes: 0
Views: 146
Reputation: 13682
You should use communicate
and wait
Example:
import subprocess
cmd="x.sh"
prc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
prc.stdin.write("yo\n")
stdout, stderr = prc.communicate()
prc.wait()
print (stdout)
Upvotes: 1