如果您知道提示的外观,那么您可以按照@Michael 的建议使用字符串操作来获得所需的输出:
import sys
from subprocess import Popen, PIPE
p = Popen([sys.executable, "names.py"], stdin=PIPE, stdout=PIPE,
universal_newlines=True)
output = p.communicate("Sue\n")[0]
prompt = "name? "
print(output.replace(prompt, prompt + "\n"))
输出
I am Joe.
What is your name?
Hi Sue !
如果您不知道提示的外观,那么如果子进程在非交互式运行时使用块缓冲,@Exp 建议的基于超时的解决方案可能不起作用。虽然它确实适用于names.py
. 这是一个基于超时的解决方案,它使用select
而不是线程来读取输出:
import os
import sys
from select import select
from subprocess import Popen, PIPE
timeout = 1 # seconds
with Popen([sys.executable, 'names.py'],
stdin=PIPE, stdout=PIPE, bufsize=0) as p:
while True:
ready = select([p.stdout], [], [], timeout)[0]
if ready: # there is something to read
data = os.read(p.stdout.fileno(), 512)
if not data: # EOF
break
sys.stdout.buffer.write(data) # echo subprocess output
elif p.poll() is None: # timeout, but subprocess is still running
print("") # print newline after the prompt
p.stdin.write(b"Sue\n") # answer the prompt
else: # subprocess exited
break
它在延迟后产生与第一个代码示例相同的输出。
通常,pexpect
可用于模拟子进程的交互模式。
如果您知道提示的样子:
import sys
import pexpect
print(pexpect.run(sys.executable + " -mnames", events={r'name\? ': 'Sue\n'}))
# note: it echos our answer too (it can be avoided if necessary)
输出
I am Joe.
What is your name? Sue
Hi Sue !
这是一个基于超时的解决方案,可以避免回显答案:
import sys
import pexpect # pip install pexpect-u
child = pexpect.spawn(sys.executable + " -mnames", timeout=1)
child.logfile_read = sys.stdout # echo subprocess output
child.expect(pexpect.TIMEOUT)
print("") # print newline after the prompt
child.setecho(False) # don't echo our answer
child.sendline('Sue')
child.expect(pexpect.EOF)
child.close()
要使用 复制它subprocess
,pty
可以使用模块:
import os
import pty
import sys
from select import select
from subprocess import Popen, STDOUT
timeout = 1 # seconds
master_fd, slave_fd = pty.openpty()
with Popen([sys.executable, 'names.py'],
stdin=slave_fd, stdout=slave_fd, stderr=STDOUT,
bufsize=0) as p:
while True:
ready = select([master_fd], [], [], timeout)[0]
if ready: # there is something to read
data = os.read(master_fd, 512)
if not data: # EOF
break
sys.stdout.buffer.write(data) # echo subprocess output
elif p.poll() is None: # timeout, but subprocess is still running
# assume that child process waits for input after printing the prompt
answer = b"Sue\n"
os.write(master_fd, answer) # asnwer the prompt
os.read(master_fd, len(answer)) # don't echo our answer
else: # subprocess exited
break
os.close(slave_fd)
os.close(master_fd)