2017-08-17 1 views
1

Je voudrais apprendre comment appeler une fonction de manière asynchrone dans Python3. Je pense que Tornado peut le faire. À l'heure actuelle, mon code retourne rien sur la ligne de commande:Appel de fonction asynchrone

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

async def count(end): 
    """Print message when start equals end.""" 
    start = 0 
    while True: 
     if start == end: 
      print('start = {0}, end = {1}'.format(start, end)) 
      break 
     start = start + 1 

def main(): 

    # Start counting. 
    yield count(1000000000) 

    # This should print while count is running. 
    print('Count is running. Async!') 

if __name__ == '__main__': 
    main() 

Merci

Répondre

1

Pour appeler une fonction async, vous devez fournir une boucle d'événement pour le gérer. Si vous avez une application Tornado, il fournit une telle boucle, ce qui vous permet de faire vos gestionnaires asynchrones:

from tornado.web import RequestHandler, url 
from tornado.httpserver import HTTPServer 
from tornado.ioloop import IOLoop 


async def do_something_asynchronous(): 
    # e.g. call another service, read from database etc 
    return {'something': 'something'} 


class YourAsyncHandler(RequestHandler): 

    async def get(self): 
     payload = await do_something_asynchronous() 
     self.write(payload) 


application = web.Application([ 
    url(r'/your_url', YourAsyncHandler, name='your_url') 
]) 

http_server = HTTPServer(application) 
http_server.listen(8000, address='0.0.0.0') 
IOLoop.instance().start() 

En dehors d'une application Tornado vous pouvez obtenir la boucle d'événements à partir de plusieurs fournisseurs, y compris le intégré dans asyncio bibliothèque:

import asyncio 
event_loop = asyncio.get_event_loop() 
try: 
    event_loop.run_until_complete(do_something_asynchronous()) 
finally: 
    event_loop.close() 
+1

Merci, Berislav :) –