我正在尝试使用subprocess.Popen class
与外部程序进行交互。外部程序接受输入并返回输出。我正在关注here中的示例,但似乎Popen
在几次互动后停止工作。这是一个例子:
这是test.sh
# test.sh
#!/bin/bash
while true; do
echo Hello, who am I talking to?
read varname
echo It\'s nice to meet you $varname
done
在python 3中运行此代码
import subprocess
import io
print('One line at a time:')
proc = subprocess.Popen(
'test.sh',
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
stdin = io.TextIOWrapper(
proc.stdin,
encoding='utf-8',
line_buffering=True, # send data on newline
)
stdout = io.TextIOWrapper(
proc.stdout,
encoding='utf-8',
)
for i in range(5):
line = '{}\n'.format(i)
stdin.write(line)
time.sleep(1)
output = stdout.readline()
print(output.rstrip())
remainder = proc.communicate()[0].decode('utf-8')
print(remainder)
这是我得到的输出:
One line at a time:
Hello, who am I talking to?
It's nice to meet you 0
Hello, who am I talking to?
It's nice to meet you 1
Hello, who am I talking to?
该程序在此之后挂起。
那么为什么Popen停止在这个例子中工作?