为什么" subprocess.Popen.stdin.write"命令似乎失败了?
#!/usr/bin/env python3
# coding=utf-8
import os
import subprocess
bash = subprocess.Popen(['bash'],
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
(shell = True:见编辑2)
bash.stdin.write(b'echo foo\n')
print(bash.stdout.readline())
bash.stdin.write(b'echo bar\n')
print(bash.stdout.readline())
编辑:它在第一个subprocess.Popen.stdout.readline()处阻塞,可能是因为subprocess.Popen.stdout中没有行。它打算打印出来:
foo
bar
编辑2:这仍然挂起。
答案 0 :(得分:0)
只要您运行GNU / Linux(可能是其他人,未经过测试)并安装pexpect(“pip install pexpect”),我的问题的答案就有效。
#!/usr/bin/env python3
# coding=utf-8
"""
Python command line software control example
"""
import pexpect
encode = 'UTF-8'
bash = pexpect.spawn('/usr/bin/env bash', encoding=encode)
bash.sendline('echo foo')
print(bash.readline())
bash.sendline('echo bar')
print(bash.readline())