¿Cómo usar async / await en Python 3.5?


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

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

foo()

No pude hacer este ejemplo simple para ejecutar:

RuntimeWarning: coroutine 'foo' was never awaited foo()
Author: Martijn Pieters, 2015-09-27

2 answers

La ejecución de corrutinas requiere un bucle de eventos . Utilice el asyncio() biblioteca para crear una:

import asyncio

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

También ver el Tareas y corrutinas capítulo de la documentación asyncio .

Tenga en cuenta sin embargo que time.sleep() es no un objeto disponible. Devuelve None por lo que se obtiene una excepción después de 1 segundo:

>>> 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

Debe utilizar el asyncio.sleep() corrutina en su lugar:

async def foo():
    await asyncio.sleep(1)
 64
Author: Martijn Pieters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-06 23:31:03

Si ya tiene un bucle en ejecución (con algunas otras tareas), puede agregar nuevas tareas con:

asyncio.ensure_future(foo())

De lo contrario podría obtener

The event loop is already running

Error.

 2
Author: lenooh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-09 13:06:49