ubuntu

Ubuntu Python异步编程

小樊
40
2025-10-01 19:08:11
栏目: 编程语言

在Ubuntu上使用Python进行异步编程,通常会使用asyncio库,这是Python 3.4及以上版本的标准库,用于编写并发代码。此外,还有第三方库如aiohttp用于异步HTTP请求,aiomysqlaiopg分别用于异步操作MySQL和PostgreSQL数据库等。

以下是一个简单的异步编程示例,使用asyncio创建一个异步函数并在其中执行一些异步操作:

import asyncio

async def my_coroutine(seconds):
    print(f"Coroutine started, waiting for {seconds} seconds...")
    await asyncio.sleep(seconds)
    print("Coroutine finished.")

async def main():
    # 创建一个任务列表
    tasks = [
        asyncio.create_task(my_coroutine(2)),
        asyncio.create_task(my_coroutine(3)),
        asyncio.create_task(my_coroutine(1)),
    ]
    
    # 等待所有任务完成
    await asyncio.gather(*tasks)

# Python 3.7及以上版本可以直接运行
asyncio.run(main())

# 对于Python 3.6,需要使用事件循环
# loop = asyncio.get_event_loop()
# loop.run_until_complete(main())
# loop.close()

在这个例子中,my_coroutine是一个异步函数,它模拟了一个耗时的操作,通过await asyncio.sleep(seconds)来模拟。main函数中创建了三个这样的任务,并使用asyncio.gather来并发执行它们。

如果你想要进行异步HTTP请求,可以使用aiohttp库:

import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = ['http://example.com', 'http://example.org', 'http://example.net']
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        responses = await asyncio.gather(*tasks)
        for response in responses:
            print(response[:100])  # 打印每个响应的前100个字符

# Python 3.7及以上版本可以直接运行
asyncio.run(main())

# 对于Python 3.6,需要使用事件循环
# loop = asyncio.get_event_loop()
# loop.run_until_complete(main())
# loop.close()

在这个例子中,fetch函数用于发起异步HTTP GET请求,main函数中并发地对多个URL发起请求,并打印出每个响应的前100个字符。

要开始使用这些库,你需要先安装它们。可以使用pip来安装:

pip install aiohttp

确保你的Python环境是3.4以上版本,因为asyncio是在Python 3.4中引入的。如果你使用的是Ubuntu,可以通过以下命令来安装Python 3(如果尚未安装):

sudo apt update
sudo apt install python3 python3-pip

然后,你可以使用pip3来安装Python 3的包。

0
看了该问题的人还看了