异步 & 异步获取命令输出 #69
Labels
blog: programming
@post
This is a blog post
tag: python
|178224075-90b8a69b-903e-4ac0-8e10-f9fbac8c9e9a.png
View Post on Blog
This post was originally created at 2020-02-05T18:53:16+08:00
Tested with Python 3.7
异步
异步和多线程比较而言,就是在应该停的地方停下,让给另一个任务。这样就使任务之间的交替变得更可控,不像多线程一样会动不动出现资源竞争的操作。
简单例子
From https://www.tornadoweb.org/en/stable/guide/async.html
synchronous:
asynchronous:
虽然看起来除了
async await
之外和同步的没有什么区别,但是阻塞的函数并不能直接改成异步的函数,因为异步函数会立即返回,而且写程序的时候要明确告知什么时候停下。接下来详细讨论一下。Get Your Hands Dirty!
Based on https://realpython.com/async-io-python/
只是直接调用
count()
,会返回<coroutine object count at ...>
,而并不会立即执行,这和 JS 不一样。插播 JS:但是在一个异步函数里调用而不用
await
变现,会直接报错:这又和 JS 不一样。
如果不使用
await asyncio.sleep
,而是使用time.sleep
来模拟一个阻塞的操作:没有切入点,只好顺序执行
如果修改
main
,成为一个循环:因为
await
会等到函数结束后才进行下一步操作。asyncio.gather(count(), count(), count())
正是为了让它们一起运行。获取命令输出
注意 Windows 下要指定路径
这里的
iter
为不常见用法,指一直调用此函数,直至返回b''
或者使用
with
:或者
异步获取命令输出
可惜上述是阻塞的,不能用于异步。这就需要
asyncio.subprocess
出场了。async for
?is equivalent to
如果不用类呢,就会是这个样子:
The text was updated successfully, but these errors were encountered: