【发布时间】:2017-08-09 23:17:01
【问题描述】:
我正在尝试将这个关键的“去抖动”逻辑从 Javascript 转换为 Python。
function handle_key(key) {
if (this.state == null) {
this.state = ''
}
this.state += key
clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
console.log(this.state)
}, 500)
}
handle_key('a')
handle_key('b')
这个想法是后续按键会延长超时时间。 Javascript 版本打印:
ab
我不想翻译 JS 超时函数,我宁愿使用 asyncio 的惯用 Python。我在 Python (3.5) 中的尝试如下,但它不起作用,因为 global_state 在我期望的时候实际上并没有更新。
import asyncio
global_state = ''
@asyncio.coroutine
def handle_key(key):
global global_state
global_state += key
local_state = global_state
yield from asyncio.sleep(0.5)
#if another call hasn't modified global_state we print it
if local_state == global_state:
print(global_state)
@asyncio.coroutine
def main():
yield from handle_key('a')
yield from handle_key('b')
ioloop = asyncio.get_event_loop()
ioloop.run_until_complete(main())
打印出来:
a
ab
我已经研究了 asyncio Event, Queue and Condition,但我不清楚如何使用它们。您将如何使用 Python 的 asyncio 实现所需的行为?
编辑
关于我想如何使用handle_keys 的更多详细信息。我有一个异步函数来检查按键。
@asyncio.coroutine
def check_keys():
keys = driver.get_keys()
for key in keys:
yield from handle_key(key)
这又与其他程序任务一起安排
@asyncio.coroutine
def main():
while True:
yield from check_keys()
yield from do_other_stuff()
ioloop = asyncio.get_event_loop()
ioloop.run_until_complete(main())
Qeek's use of asyncio.create_task and asyncio.gather 是有道理的。但是我将如何在这样的循环中使用它呢?或者是否有另一种方法来安排允许handle_keys 调用“重叠”的异步任务?
【问题讨论】:
标签: python python-3.x python-asyncio