python调用pipe_python中subprocess.PIPE上的非阻塞读取

Python 3.4 为异步IO 模块引入了新的临时API。asyncio

这种方法类似于twisted@Bryan Ward的基于答案的答案 - 定义一个协议,一旦数据准备就调用它的方法:#!/usr/bin/env python3import asyncioimport osclass SubprocessProtocol(asyncio.SubprocessProtocol):

def pipe_data_received(self, fd, data):

if fd == 1: # got stdout data (bytes)

print(data)

def connection_lost(self, exc):

loop.stop() # end loop.run_forever()if os.name == 'nt':

loop = asyncio.ProactorEventLoop() # for subprocess' pipes on Windows

asyncio.set_event_loop(loop)else:

loop = asyncio.get_event_loop()try:

loop.run_until_complete(loop.subprocess_exec(SubprocessProtocol,

"myprogram.exe", "arg1", "arg2"))

loop.run_forever()finally:

loop.close()#!/usr/bin/env python3.5import asyncioimport localeimport sysfrom asyncio.subprocess import PIPEfrom contextlib import closing

async def readline_and_kill(*args):

# start child process

process = await asyncio.create_subprocess_exec(*args, stdout=PIPE)

# read line (sequence of bytes ending with b'\n') asynchronously

async for line in process.stdout:

print("got line:", line.decode(locale.getpreferredencoding(False)))

break

process.kill()

return await process.wait() # wait for the child process to exitif sys.platform == "win32":

loop = asyncio.ProactorEventLoop()

asyncio.set_event_loop(loop)else:

loop = asyncio.get_event_loop()with closing(loop):

sys.exit(loop.run_until_complete(readline_and_kill(

"myprogram.exe", "arg1", "arg2")))

readline_and_kill() 执行以下任务:启动子进程,将其stdout重定向到管道

从子进程'stdout异步读取一行

杀死子进程

等它退出

如有必要,每个步骤都可以通过超时秒限制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值