gpt4 book ai didi

python - 异步函数调用

转载 作者:太空宇宙 更新时间:2023-11-03 14:53:44 26 4
gpt4 key购买 nike

我想学习如何在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()

谢谢

最佳答案

要调用异步函数,您需要提供一个事件循环来处理它。如果您有 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 应用程序之外,您可以从任意数量的提供程序获取事件循环,包括内置的 asyncio图书馆:

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

关于python - 异步函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45739337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com