【问题标题】:python subprocess Popen is not delivering stdinpython子进程Popen没有提供标准输入
【发布时间】:2017-07-20 14:48:23
【问题描述】:

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

我有这个互动程序:

#!/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''

有什么想法吗?

【问题讨论】:

  • 程序将无法回显该行直到你给它一个完整的行 - 尝试将\n 放在你的字符串的末尾'重新写入程序。
  • 不行,readline() 还是卡住了
  • @Patrik,您收到想要的答案了吗?
  • 不,我没有,但我没有尝试刷新交互式程序中的输出缓冲区

标签: python subprocess popen interactive


【解决方案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)

【讨论】:

  • 沟通是不行的。文档说“等待进程终止”,但我需要一个交互式解决方案。根据我收到的内容向标准输入发送一些内容,读取 stout,向标准输入发送其他内容