Python 异步函数调用

Python 异步函数调用,python,tornado,Python,Tornado,我想学习如何在Python3中异步调用函数。我想我能做到。当前,我的代码在命令行上不返回任何内容: #!/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 = {

我想学习如何在Python3中异步调用函数。我想我能做到。当前,我的代码在命令行上不返回任何内容:

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

感谢调用异步函数,您需要提供一个事件循环来处理它。如果您有Tornado应用程序,它会提供这样一个循环,允许您使处理程序异步:

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()
在Tornado应用程序之外,您可以从任意数量的提供者(包括内置库)获取事件循环:

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