python 结束循环事件_中断事件循环后,正确的清理方法是什么?

我有一个事件循环,它作为命令行工具的一部分运行一些联合例程。用户可以使用通常的Ctrl+C来中断工具,此时我希望在中断的事件循环之后正确地清理。

这是我试过的。import asyncio

@asyncio.coroutine

def shleepy_time(seconds):

print("Shleeping for {s} seconds...".format(s=seconds))

yield from asyncio.sleep(seconds)

if __name__ == '__main__':

loop = asyncio.get_event_loop()

# Side note: Apparently, async() will be deprecated in 3.4.4.

# See: https://docs.python.org/3.4/library/asyncio-task.html#asyncio.async

tasks = [

asyncio.async(shleepy_time(seconds=5)),

asyncio.async(shleepy_time(seconds=10))

]

try:

loop.run_until_complete(asyncio.gather(*tasks))

except keyboardInterrupt as e:

print("Caught keyboard interrupt. Canceling tasks...")

# This doesn't seem to be the correct solution.

for t in tasks:

t.cancel()

finally:

loop.close()

运行此命令并点击Ctrl+C将生成:$ python3 asyncio-keyboardinterrupt-example.py

Shleeping for 5 seconds...

Shleeping for 10 seconds...

^CCaught keyboard interrupt. Canceling tasks...

Task was destroyed but it is pending!

task: wait_for= cb=[gather.._done_callback(1)() at /usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/asyncio/tasks.py:587]>

Task was destroyed but it is pending!

task: wait_for= cb=[gather.._done_callback(0)() at /usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/asyncio/tasks.py:587]>

显然,我没有正确地清理。我想也许在任务上调用cancel()是实现这一点的方法。

中断事件循环后,正确的清理方法是什么?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值