如何在 Python 3.5 中使用 async/await?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32808893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:18:47  来源:igfitidea点击:

How to use async/await in Python 3.5?

pythonpython-3.xasync-awaitcoroutinepython-3.5

提问by smilingpoplar

#!/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()

采纳答案by Martijn Pieters

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

运行协程需要一个事件循环。使用asyncio()创建一个:

import asyncio

# Python 3.7+
asyncio.run(foo())

or

或者

# Python 3.6 and older
loop = asyncio.get_event_loop()
loop.run_until_complete(foo())

Also see the Tasks and Coroutineschapter of the asynciodocumentation. If you already have a loop running, you'd want to run additional coroutines concurrently by creating a task (asyncio.create_task(...)in Python 3.7+, asyncio.ensure_future(...)in older versions).

另请参阅文档任务和协程章节asyncio。如果您已经有一个循环在运行,您可能希望通过创建一个任务(asyncio.create_task(...)在 Python 3.7+ 中,asyncio.ensure_future(...)在旧版本中)同时运行其他协程。

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

但是请注意,time.sleep()不是一个awaitable对象。它返回,None因此您会在 1 秒后收到异常:

>>> asyncio.run(foo())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/.../lib/python3.7/asyncio/base_events.py", line 573, in run_until_complete
    return future.result()
  File "<stdin>", line 2, in foo
TypeError: object NoneType can't be used in 'await' expression

In this case you should use the asyncio.sleep()coroutineinstead:

在这种情况下,您应该改用asyncio.sleep()协程

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

which is cooperates with the loop to enable other tasks to run. For blocking code from third-party libraries that do not have asyncio equivalents, you could run that code in an executor pool. See Running Blocking Codein the asyncio development guide.

它与循环配合使其他任务能够运行。要阻止来自没有 asyncio 等效项的第三方库的代码,您可以在executor pool 中运行该代码。请参阅asyncio 开发指南中的运行阻塞代码

回答by lenooh

If you already have a loop running (with some other tasks), you can add new tasks with:

如果您已经有一个循环在运行(还有一些其他任务),您可以使用以下命令添加新任务:

asyncio.ensure_future(foo())

otherwise you might get

否则你可能会得到

The event loop is already running

error.

错误。