2015-09-27 13 views
46
#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
import time 

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

foo() 

non ho potuto fare questa semplice esempio morto a correre:Come usare async/await in Python 3.5?

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

risposta

56

coroutine in corso richiede un ciclo evento. Utilizzare il asyncio() library per creare uno:

import asyncio 

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

vedere anche la Tasks and Coroutines chapter of the asyncio documentation.

Nota tuttavia che time.sleep() è non un oggetto attendibile. Esso restituisce None in modo da ottenere un'eccezione dopo 1 secondo:

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

si dovrebbe usare il asyncio.sleep() coroutine invece:

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