首页 > 编程语言 >Asyncio in Python and Concurrency tasks

Asyncio in Python and Concurrency tasks

时间:2024-03-10 14:23:26浏览次数:23  
标签:tasks run Python self command Concurrency loop asyncio

Asyncio Library and Concurrency tasks in Python

The asyncio library is a Python standard library module used for writing single-threaded concurrent code using coroutines, multiplexing I/O access, and running network clients and servers. It provides a framework that revolves around the event loop, enabling asynchronous programming, which is particularly useful for I/O-bound and high-level structured network code.

Here's a brief overview of its key features:

  1. Event Loop : The core of asyncio is the event loop. It's the central execution device that manages and distributes the execution of different tasks. It's used to schedule asynchronous tasks and callbacks, handle network I/O events, and run subprocesses.
  2. Coroutines and Tasks : Coroutines are the fundamental units of work in asyncio, declared using the async def syntax. They are used to write asynchronous functions. A Task is then used to schedule coroutines concurrently.
  3. Futures : A Future is a special low-level awaitable object representing an eventual result of an asynchronous operation.
  4. Synchronization Primitives : asyncio provides primitives like locks, events, conditions, and semaphores, similar to those in the threading module, but designed for the asyncio tasks.
  5. Subprocesses : It supports the creation and management of subprocesses.
  6. Queues : It provides a queue class that can be used to distribute work between different coroutines.
  7. Streams : High-level API for working with network connections, allowing easy implementation of protocols and transports.
  8. Exception Handling : asyncio tasks have their own exception handling. Exceptions are stored and can be retrieved when the task is done.
import asyncio

async def main():
    print('Hello')
    await asyncio.sleep(1)
    print('World')

asyncio.run(main())

# Example in concurrency 
async def fetch_data():
    reader, writer = await asyncio.open_connection('example.com', 80)
    request_header = 'GET / HTTP/1.0\r\nHost: example.com\r\n\r\n'
    writer.write(request_header.encode())
    await writer.drain()
    data = await reader.read(100)
    print(data.decode())
    writer.close()
    await writer.wait_closed()

asyncio.run(fetch_data())

Unit test of asycio

import unittest
import asyncio
from your_module import AsyncLocalClient  # Import your AsyncLocalClient class

class TestAsyncLocalClient(unittest.TestCase):

    def setUp(self):
        self.client = AsyncLocalClient()

    def test_command_execution(self):
        loop = asyncio.get_event_loop()
        command = 'echo "Hello World"'
        result = loop.run_until_complete(self.client.run_command(command))
        self.assertIn("Hello World", result.stdout)
        self.assertEqual(result.exit_code, 0)

    def test_command_failure(self):
        loop = asyncio.get_event_loop()
        command = 'ls non_existent_directory'
        result = loop.run_until_complete(self.client.run_command(command))
        self.assertNotEqual(result.exit_code, 0)
        self.assertTrue(result.stderr)

    def test_async_execution(self):
        loop = asyncio.get_event_loop()
        commands = ['sleep 1', 'sleep 2', 'echo "async test"']
        tasks = [self.client.run_command(cmd) for cmd in commands]
        results = loop.run_until_complete(asyncio.gather(*tasks))
        self.assertEqual(len(results), 3)
        self.assertIn("async test", results[-1].stdout)

if __name__ == '__main__':
    unittest.main()

run test with python -m unittest test_async_local_client.py

Examples use asyncio

async def call(command):
    vc_client = AsyncLocalClient()
    try:
        tasks = [vc_client.run_command(command)]
        output = await asyncio.gather(*tasks,return_exceptions=True)
    except Exception as e:
        print(f"An error occurred: {type(e).__name__}, {e}")
    return output
# Test run it like:
asyncio.run(call(command), debug=True)

  • When need to include the environment using asyncio
env = os.environ.copy()
env['LD_LIBRARY_PATH'] = '[path]/lib:' + env.get('LD_LIBRARY_PATH', '')
  • How to create multi-tasks and gather their output
async def call(command):
    client = AsyncLocalClient()
    task = asyncio.create_task(call_async_func(cmds), name=str(idx))
    tasks.append(task)
    outputs = await asyncio.gather(*tasks, return_exceptions=True)
    return outputs

def main():
    results = asyncio.run(call(command))

标签:tasks,run,Python,self,command,Concurrency,loop,asyncio
From: https://www.cnblogs.com/holylandofdora/p/18063973

相关文章

  • 卸载环境所有python包(第三方库)
    打开CMD终端,查看已安装库:piplist一个个删除需要执行:pipuninstall包名;那么如何一次性删除所有的包呢?首先需要执行以下代码: pipfreeze>modules.txt这时候就能够把所有的第三方模块的模块名称以及第三方模块的版本号等等信息保存在了这个modules.txt文件中,之后的操作就是......
  • forward reference in python
    ForwardReferenceinpythonThereisacodesnippetlike:@propertydefanalyses(self)->"AnalysesHubWithDefault":result=self._analysesifresultisNone:raiseValueError("Cannotaccessanalysesthisearlyinproject......
  • 【Python使用】python高级进阶知识md总结第2篇:HTTP 请求报文,HTTP响应报文【附代码文
    python高级进阶全知识知识笔记总结完整教程(附代码资料)主要内容讲述:操作系统,虚拟机软件,Ubuntu操作系统,Linux内核及发行版,查看目录命令,切换目录命令,绝对路径和相对路径,创建、删除文件及目录命令,复制、移动文件及目录命令,终端命令格式的组成,查看命令帮助。HTTP请求报文,HTTP响应报文......
  • 解决python导入csv文件报错
    python编码报错:UnicodeDecodeError:‘utf-8‘codeccan‘tdecodebyte0xbcinposition2:invalidstartbyt_unicodedecodeerror:'utf-8'codeccan'tdecodebyt-CSDN博客报错原因是:UnicodeDecodeError:'utf-8'codeccan'tdecodebyte0xb5in......
  • Python 潮流周刊第 41 期(摘要),赠书5本
    本周刊由Python猫出品,精心筛选国内外的250+信息源,为你挑选最值得分享的文章、教程、开源项目、软件工具、播客和视频、热门话题等内容。愿景:帮助所有读者精进Python技术,并增长职业和副业的收入。周刊全文:https://pythoncat.top/posts/2024-03-09-weekly《Python工匠》专注......
  • Python基于TCP实现聊天功能
    Server端importsocketimportqueueimportthreadingimporttimeserversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)host=socket.gethostname()print("服务器IP:"+socket.gethostbyname(host))serversocket.bind((host,9090))serversock......
  • python Ai 应用开发基础训练,字符串,字典,文件
    --------------------------------------  编程能是大模型应用的天花板..................................................................所以要好好将大模型应用在企业一定要好好练好最看不起的一环,基础能力字符串处理 本文档来自老男孩培训Alex课程记录,我在2017年......
  • python+pytest接口自动化之测试函数、测试类/测试方法的封装
    前言今天呢,笔者想和大家聊聊python+pytest接口自动化中将代码进行封装,只有将测试代码进行封装,才能被测试框架识别执行。例如单个接口的请求代码如下:importrequestsheaders={"user-agent":"Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,l......
  • 【Python使用】python高级进阶知识md总结第1篇:My Awesome Book【附代码文档】
    python高级进阶全知识知识笔记总结完整教程(附代码资料)主要内容讲述:MyAwesomeBook,MyAwesomeBook。MyAwesomeBook,MySQL数据库。MyAwesomeBook,聚合函数。MyAwesomeBook,创建表并给某个字段添加数据。MyAwesomeBook,闭包。MyAwesomeBook,路由列表功能开发。MyAwesomeBoo......
  • vscode编写python
    安装插件打开cmd创建虚拟环境C:\Users\ychen>condacreate-nenv_devpython=3.10.4Fetchingpackagemetadata.................Solvingpackagespecifications:.PackageplanforinstallationinenvironmentC:\ProgramData\Anaconda3\envs\env_dev:Thefo......