如何使用异步在Python 3.5 /等待? [英] How to use async/await in Python 3.5?

查看:799
本文介绍了如何使用异步在Python 3.5 /等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #!的/ usr / bin中/ env的python3
# - * - 编码:UTF-8 - * -
进口时间异步高清富():
  等待time.sleep(1)富()

我不能让这个死简单的例子来运行:

  RuntimeWarning:协程'富'是从来没有期待已久的富()


解决方案

运行协同程序需要的事件循环的。使用 ASYNCIO()来创建一个

 进口ASYNCIO循环= asyncio.get_event_loop()
loop.run_until_complete(富())
loop.close()

另请参阅任务和协同程序的的 ASYNCIO 文档

然而要注意 time.sleep()是的的一个awaitable对象。它返回,所以你以后得到一个例外情况1秒:

 >>> loop.run_until_complete(富())
回溯(最近通话最后一个):
  文件<&标准输入GT;,1号线,上述<&模块GT;
  文件/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.5/asyncio/base_events.py,线路342,在run_until_complete
    返回future.result()
  文件/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.5/asyncio/futures.py,线路274,在结果
    提高self._exception
  文件/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.5/asyncio/tasks.py,239线,在_step
    结果= coro.send(值)
  文件<&标准输入GT;,2号线,在富
类型错误:对象NoneType不能使用'等待'前pression

您应该使用<$c$c>asyncio.sleep()协程来代替:

 异步高清富():
    等待asyncio.sleep(1)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time

async def foo():
  await time.sleep(1)

foo()

I couldn't make this dead simple example to run:

RuntimeWarning: coroutine 'foo' was never awaited foo()

解决方案

Running coroutines requires an event loop. Use the asyncio() library to create one:

import asyncio

loop = asyncio.get_event_loop()
loop.run_until_complete(foo())
loop.close()

Also see the Tasks and Coroutines chapter of the asyncio documentation.

Note however that time.sleep() is not an awaitable object. It returns None so you get an exception after 1 second:

>>> loop.run_until_complete(foo())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.5/asyncio/base_events.py", line 342, in run_until_complete
    return future.result()
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.5/asyncio/futures.py", line 274, in result
    raise self._exception
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.5/asyncio/tasks.py", line 239, in _step
    result = coro.send(value)
  File "<stdin>", line 2, in foo
TypeError: object NoneType can't be used in 'await' expression

You should use the asyncio.sleep() coroutine instead:

async def foo():
    await asyncio.sleep(1)

这篇关于如何使用异步在Python 3.5 /等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆