python子进程Popen没有提供stdin

时间:2017-07-20 14:48:24

标签: python subprocess popen interactive

我知道有很多次问过类似的问题,但我没有设法将这些解决方案应用到我的案例中。

我有这个互动节目:

#!/bin/sh                                                                                                                                                                   

echo "banana"                                                                                                                                                               
while true                                                                                                                                                                  
do                                                                                                                                                                          
    read line                                                                                                                                                               
    echo $line                                                                                                                                                              
done

我试图通过python与它进行通信,但这种情况发生了:

> 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())

有时会挂在那里,但有时会打印

b''

任何想法?

1 个答案:

答案 0 :(得分:1)

您应该使用communicatewait

示例:

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)