2017-08-17 28 views
1

Python3で関数を非同期に呼び出す方法を学びたいと思います。私はTornadoがこれを行うことができると思います。現在、私のコードは、コマンドラインに何も返しません:非同期関数呼び出し

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

おかげ

答えて

1

を非同期関数を呼び出すには、それを処理するためのイベントループを提供する必要があります。あなたが内蔵など、プロバイダの任意の数からイベントループを得ることができます竜巻アプリの外

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

:あなたはトルネードアプリを持っている場合、それはあなたがあなたのハンドラは、非同期にすることを可能にするようなループを提供し、 asyncioライブラリ:

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

ありがとう、Berislav :) –

関連する問題