import asyncio
import os
import time
from asyncio.subprocess import PIPE, STDOUT
from threading import Thread
@asyncio.coroutine
def do_task(domain, loop):
p = yield from asyncio.create_subprocess_exec('ping', '-c 4 -w 10', domain, stdout=PIPE,loop=loop)
#task = asyncio.ensure_future(p.stdout.read(),loop=loop)
#task = asyncio.ensure_future(p.communicate())
task = asyncio.Task(p.stdout.read(), loop=loop)
done, pending = yield from asyncio.wait([task], timeout=2, loop=loop)
if pending:
print('timeout...........')
# timeout
if p.returncode is None:
# kill the subprocess, then `await future` will return soon
try:
p.kill()
except ProcessLookupError:
pass
output = yield from task
print(output.decode('utf-8'))
print('-----------OK----------')
def do_loop(loop):
asyncio.set_event_loop(loop)
print('loop starting...................')
loop.run_forever()
loop= asyncio.new_event_loop()
Thread(target=do_loop, args=(loop,)).start()
domain = 'www.sina.com.cn'
asyncio.run_coroutine_threadsafe(do_task(domain, loop), loop)
#loop.call_soon_threadsafe(asyncio.async, do_task(domain, loop))
print('after run_coroutine_threadsafe')
#loop.run_forever()
上述代码演示了 asyncio 中create_subprocess_exec, timeout的用法。运行环境 python 3.5.2。
注: python3不同版本间的asyncio库的接口差异有点大,要注意。在python3.6的版本中,上述代码是无法正常运行的。