怎么用python控制另一个程序_Python3详细控制另一个进程的I/O

如果您知道提示的外观,那么您可以使用字符串操作来获得所需的输出@Michael suggested: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"))

输出

^{pr2}$

如果您不知道提示的外观,那么如果子进程在非交互运行时使用块缓冲,则the timeout-based solution suggested by @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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值