当前位置: 首页 > news >正文

MetaGPT中的教程助手:TutorialAssistant

1. 提示词

COMMON_PROMPT = """
You are now a seasoned technical professional in the field of the internet. 
We need you to write a technical tutorial with the topic "{topic}".
"""DIRECTORY_PROMPT = (COMMON_PROMPT+ """
Please provide the specific table of contents for this tutorial, strictly following the following requirements:
1. The output must be strictly in the specified language, {language}.
2. Answer strictly in the dictionary format like {{"title": "xxx", "directory": [{{"dir 1": ["sub dir 1", "sub dir 2"]}}, {{"dir 2": ["sub dir 3", "sub dir 4"]}}]}}.
3. The directory should be as specific and sufficient as possible, with a primary and secondary directory.The secondary directory is in the array.
4. Do not have extra spaces or line breaks.
5. Each directory title has practical significance.
"""
)
CONTENT_PROMPT = (COMMON_PROMPT+ """
Now I will give you the module directory titles for the topic. 
Please output the detailed principle content of this title in detail. 
If there are code examples, please provide them according to standard code specifications. 
Without a code example, it is not necessary.The module directory titles for the topic is as follows:
{directory}Strictly limit output according to the following requirements:
1. Follow the Markdown syntax format for layout.
2. If there are code examples, they must follow standard syntax specifications, have document annotations, and be displayed in code blocks.
3. The output must be strictly in the specified language, {language}.
4. Do not have redundant output, including concluding remarks.
5. Strict requirement not to output the topic "{topic}".
"""
)

2. 两个动作: 写文档大纲 (WriteDirectory) 和文档内容 (WriteContent)

from typing import Dictfrom metagpt.actions import Action
from metagpt.utils.common import OutputParserclass WriteDirectory(Action):"""Action class for writing tutorial directories.Args:name: The name of the action.language: The language to output, default is "Chinese"."""name: str = "WriteDirectory"language: str = "Chinese"async def run(self, topic: str, *args, **kwargs) -> Dict:"""Execute the action to generate a tutorial directory according to the topic.Args:topic: The tutorial topic.Returns:the tutorial directory information, including {"title": "xxx", "directory": [{"dir 1": ["sub dir 1", "sub dir 2"]}]}."""prompt = DIRECTORY_PROMPT.format(topic=topic, language=self.language)resp = await self._aask(prompt=prompt)return OutputParser.extract_struct(resp, dict)class WriteContent(Action):"""Action class for writing tutorial content.Args:name: The name of the action.directory: The content to write.language: The language to output, default is "Chinese"."""name: str = "WriteContent"directory: dict = dict()language: str = "Chinese"async def run(self, topic: str, *args, **kwargs) -> str:"""Execute the action to write document content according to the directory and topic.Args:topic: The tutorial topic.Returns:The written tutorial content."""prompt = CONTENT_PROMPT.format(topic=topic, language=self.language, directory=self.directory)return await self._aask(prompt=prompt)

3. 教程助手定义

具体逻辑:第一步写文档目录,第二步,根据文档目录写每一章的内容,第三步,将内容写入markdown文件中

from datetime import datetime
from typing import Dict
from metagpt.const import get_metagpt_root
from metagpt.logs import logger
from metagpt.roles.role import Role
from metagpt.schema import Message
from metagpt.utils.file import FileTUTORIAL_PATH = get_metagpt_root()/"data"/"tutorial_docx"class TutorialAssistant(Role):"""Tutorial assistant, input one sentence to generate a tutorial document in markup format.Args:name: The name of the role.profile: The role profile description.goal: The goal of the role.constraints: Constraints or requirements for the role.language: The language in which the tutorial documents will be generated."""name: str = "Stitch"profile: str = "Tutorial Assistant"goal: str = "Generate tutorial documents"constraints: str = "Strictly follow Markdown's syntax, with neat and standardized layout"language: str = "Chinese"topic: str = ""main_title: str = ""total_content: str = ""def __init__(self, **kwargs):super().__init__(**kwargs)self.set_actions([WriteDirectory(language=self.language)])self._set_react_mode(react_mode="by_order")async def _handle_directory(self, titles: Dict) -> Message:"""Handle the directories for the tutorial document.Args:titles: A dictionary containing the titles and directory structure,such as {"title": "xxx", "directory": [{"dir 1": ["sub dir 1", "sub dir 2"]}]}Returns:A message containing information about the directory."""self.main_title = titles.get("title")directory = f"{self.main_title}\n"self.total_content += f"# {self.main_title}"actions = list(self.actions)for first_dir in titles.get("directory"):actions.append(WriteContent(language=self.language, directory=first_dir))key = list(first_dir.keys())[0]directory += f"- {key}\n"for second_dir in first_dir[key]:directory += f"  - {second_dir}\n"self.set_actions(actions)self.rc.max_react_loop = len(self.actions)return Message()async def _act(self) -> Message:"""Perform an action as determined by the role.Returns:A message containing the result of the action."""todo = self.rc.todoif type(todo) is WriteDirectory:msg = self.rc.memory.get(k=1)[0]self.topic = msg.contentresp = await todo.run(topic=self.topic)logger.info(resp)return await self._handle_directory(resp)resp = await todo.run(topic=self.topic)logger.info(resp)if self.total_content != "":self.total_content += "\n\n\n"self.total_content += respreturn Message(content=resp, role=self.profile)async def react(self) -> Message:msg = await super().react()root_path = TUTORIAL_PATH / datetime.now().strftime("%Y-%m-%d_%H-%M-%S")await File.write(root_path, f"{self.main_title}.md", self.total_content.encode("utf-8"))msg.content = str(root_path / f"{self.main_title}.md")return msg
2024-12-12 15:39:46.005 | INFO     | metagpt.const:get_metagpt_package_root:21 - Package root set to d:\llm\metagpt

4. 示例

async def main():topic = "Write a tutorial about python asyncio"role = TutorialAssistant(language="Chinese")await role.run(topic)await main()

输出:

{
"title": "Python Asyncio 异步编程教程",
"directory": [{"一、异步编程基础": ["1.1 异步编程概念","1.2 Python中的异步历史","1.3 异步编程的优势"]},{"二、Asyncio入门": ["2.1 安装与配置","2.2 Event Loop事件循环","2.3 coroutine协程","2.4 Future对象","2.5 使用async和await"]},{"三、Asyncio高级应用": ["3.1 并发执行与同步","3.2 异步网络请求","3.3 异步文件操作","3.4 异步数据库操作","3.5 异步队列"]},{"四、常见问题与解决方案": ["4.1 协程间通信","4.2 异步异常处理","4.3 性能优化","4.4 兼容性问题"]},{"五、实战案例": ["5.1 异步爬虫","5.2 异步Web服务","5.3 异步数据处理"]},{"六、附录": ["6.1 常用库与资源","6.2 最佳实践","6.3 进一步学习"]}
]
}2024-12-12 15:39:57.769 | WARNING  | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4 not found in TOKEN_COSTS.
2024-12-12 15:39:57.770 | INFO     | __main__:_act:72 - {'title': 'Python Asyncio 异步编程教程', 'directory': [{'一、异步编程基础': ['1.1 异步编程概念', '1.2 Python中的异步历史', '1.3 异步编程的优势']}, {'二、Asyncio入门': ['2.1 安装与配置', '2.2 Event Loop事件循环', '2.3 coroutine协程', '2.4 Future对象', '2.5 使用async和await']}, {'三、Asyncio高级应用': ['3.1 并发执行与同步', '3.2 异步网络请求', '3.3 异步文件操作', '3.4 异步数据库操作', '3.5 异步队列']}, {'四、常见问题与解决方案': ['4.1 协程间通信', '4.2 异步异常处理', '4.3 性能优化', '4.4 兼容性问题']}, {'五、实战案例': ['5.1 异步爬虫', '5.2 异步Web服务', '5.3 异步数据处理']}, {'六、附录': ['6.1 常用库与资源', '6.2 最佳实践', '6.3 进一步学习']}]}# 一、异步编程基础## 1.1 异步编程概念异步编程是一种编程范式,允许程序在等待某些操作完成(如I/O操作)时继续执行其他任务。与传统的同步编程不同,同步编程在等待操作完成时会阻塞当前任务的执行。异步编程可以提高程序的效率和响应性。## 1.2 Python中的异步历史Python的异步编程经历了几个阶段的发展:- Python 2.x时代:主要通过`threading`和`multiprocessing`模块实现并发。
- Python 3.0至3.3:引入了`yield`关键字和`generators`,可以通过生成器实现简单的协同程序。
- Python 3.4:引入了`asyncio`库,提供了编写单线程并发代码的框架。
- Python 3.5:引入了`async`和`await`关键字,使得异步编程更加直观和易于编写。## 1.3 异步编程的优势异步编程具有以下优势:1. 提高I/O密集型应用的性能:在等待I/O操作完成时,CPU可以切换到其他任务,从而提高资源利用率。
2. 更好的资源利用:异步编程允许使用单线程管理多个并发任务,减少了线程或进程的开销。
3. 提升用户体验:在Web应用和用户界面中,异步编程可以避免因长时间操作导致的界面冻结。以下是一个简单的使用`asyncio`的例子:```python
import asyncioasync def hello_world():print("Hello")await asyncio.sleep(1)  # 模拟I/O操作print("World")# 运行异步函数
asyncio.run(hello_world())
```请注意,上述代码应在Python 3.7及以上版本运行,因为`asyncio.run()`函数是在Python 3.7中引入的。在之前的版本中,需要使用`asyncio.get_event_loop().run_until_complete(hello_world())`来运行异步函数2024-12-12 15:40:15.460 | WARNING  | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4 not found in TOKEN_COSTS.
2024-12-12 15:40:15.462 | INFO     | __main__:_act:75 - # 一、异步编程基础## 1.1 异步编程概念异步编程是一种编程范式,允许程序在等待某些操作完成(如I/O操作)时继续执行其他任务。与传统的同步编程不同,同步编程在等待操作完成时会阻塞当前任务的执行。异步编程可以提高程序的效率和响应性。## 1.2 Python中的异步历史Python的异步编程经历了几个阶段的发展:- Python 2.x时代:主要通过`threading`和`multiprocessing`模块实现并发。
- Python 3.0至3.3:引入了`yield`关键字和`generators`,可以通过生成器实现简单的协同程序。
- Python 3.4:引入了`asyncio`库,提供了编写单线程并发代码的框架。
- Python 3.5:引入了`async`和`await`关键字,使得异步编程更加直观和易于编写。## 1.3 异步编程的优势异步编程具有以下优势:1. 提高I/O密集型应用的性能:在等待I/O操作完成时,CPU可以切换到其他任务,从而提高资源利用率。
2. 更好的资源利用:异步编程允许使用单线程管理多个并发任务,减少了线程或进程的开销。
3. 提升用户体验:在Web应用和用户界面中,异步编程可以避免因长时间操作导致的界面冻结。以下是一个简单的使用`asyncio`的例子:```python
import asyncioasync def hello_world():print("Hello")await asyncio.sleep(1)  # 模拟I/O操作print("World")# 运行异步函数
asyncio.run(hello_world())
```请注意,上述代码应在Python 3.7及以上版本运行,因为`asyncio.run()`函数是在Python 3.7中引入的。在之前的版本中,需要使用`asyncio.get_event_loop().run_until_complete(hello_world())`来运行异步函数。。
# 二、Asyncio入门## 2.1 安装与配置Asyncio 是 Python 的一个库,用于编写单线程并发代码,通过异步/等待语法。要在 Python 中使用 asyncio,你需要 Python 3.5 或更高版本。### 安装Asyncio 随 Python 3.4+ 一起安装,无需额外安装。### 配置无需特别的配置,直接在 Python 脚本中导入即可使用。```python
import asyncio
```## 2.2 Event Loop事件循环事件循环是 asyncio 程序的核心,它用来调度和执行任务。```python
# 示例:创建事件循环
loop = asyncio.get_event_loop()
try:loop.run_forever()
finally:loop.close()
```## 2.3 coroutine协程协程是使用 `async def` 定义的函数,它是异步编程的核心。```python
# 示例:定义协程
async def main():print('Hello')await asyncio.sleep(1)print('World')# 运行协程
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```## 2.4 Future对象Future 对象表示尚未完成的计算,它用来与异步执行的结果进行交互。```python
# 示例:创建 Future 对象
async def main():# 获取当前事件循环loop = asyncio.get_event_loop()# 创建一个 Future 对象future = loop.create_future()# 模拟异步操作,并在一段时间后设置结果async def set_future():await asyncio.sleep(1)future.set_result('Future is done!')# 启动任务loop.create_task(set_future())# 等待 Future 完成result = await futureprint(result)loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```## 2.5 使用async和await`async` 和 `await` 关键字用于编写异步代码。```python
# 示例:使用 async 和 await
async def say_after(delay, what):await asyncio.sleep(delay)print(what)async def main():print(f"started at {time.strftime('%X')}")await say_after(1, 'hello')await say_after(2, 'world')print(f"finished at {time.strftime('%X')}")asyncio.run(main())
```请注意,上面的示例中使用了 `asyncio.run(main())`,这是 Python 3.7+ 推荐的运行协程的方式,代替了手动获取事件循环和关闭事件循环的做法。`asyncio.run()` 应该只被调用一次,通常在主程序入口处。2024-12-12 15:40:36.272 | WARNING  | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4 not found in TOKEN_COSTS.
2024-12-12 15:40:36.274 | INFO     | __main__:_act:75 - # 二、Asyncio入门## 2.1 安装与配置Asyncio 是 Python 的一个库,用于编写单线程并发代码,通过异步/等待语法。要在 Python 中使用 asyncio,你需要 Python 3.5 或更高版本。### 安装Asyncio 随 Python 3.4+ 一起安装,无需额外安装。### 配置无需特别的配置,直接在 Python 脚本中导入即可使用。```python
import asyncio
```## 2.2 Event Loop事件循环事件循环是 asyncio 程序的核心,它用来调度和执行任务。```python
# 示例:创建事件循环
loop = asyncio.get_event_loop()
try:loop.run_forever()
finally:loop.close()
```## 2.3 coroutine协程协程是使用 `async def` 定义的函数,它是异步编程的核心。```python
# 示例:定义协程
async def main():print('Hello')await asyncio.sleep(1)print('World')# 运行协程
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```## 2.4 Future对象Future 对象表示尚未完成的计算,它用来与异步执行的结果进行交互。```python
# 示例:创建 Future 对象
async def main():# 获取当前事件循环loop = asyncio.get_event_loop()# 创建一个 Future 对象future = loop.create_future()# 模拟异步操作,并在一段时间后设置结果async def set_future():await asyncio.sleep(1)future.set_result('Future is done!')# 启动任务loop.create_task(set_future())# 等待 Future 完成result = await futureprint(result)loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```## 2.5 使用async和await`async` 和 `await` 关键字用于编写异步代码。```python
# 示例:使用 async 和 await
async def say_after(delay, what):await asyncio.sleep(delay)print(what)async def main():print(f"started at {time.strftime('%X')}")await say_after(1, 'hello')await say_after(2, 'world')print(f"finished at {time.strftime('%X')}")asyncio.run(main())
```请注意,上面的示例中使用了 `asyncio.run(main())`,这是 Python 3.7+ 推荐的运行协程的方式,代替了手动获取事件循环和关闭事件循环的做法。`asyncio.run()` 应该只被调用一次,通常在主程序入口处。# 三、Asyncio高级应用## 3.1 并发执行与同步`asyncio` 是 Python 的一个异步I/O框架,用于编写单线程并发代码,通过异步/等待语法。### 并发执行`asyncio` 允许我们并发地运行多个协程。以下是一个简单的并发执行示例:```python
import asyncioasync def say_after(delay, what):await asyncio.sleep(delay)print(what)async def main():print(f"started at {time.strftime('%X')}")# 创建两个协程对象,不立即运行coroutine1 = say_after(1, 'hello')coroutine2 = say_after(2, 'world')# 等待两个协程并发执行await asyncio.gather(coroutine1, coroutine2)print(f"finished at {time.strftime('%X')}")# 运行主协程
asyncio.run(main())
```### 同步在并发编程中,同步是确保多个任务按预期执行的机制。`asyncio` 提供了 `asyncio.Lock()` 和 `asyncio.Event()` 等同步原语。以下是一个使用 `asyncio.Lock()` 的示例:```python
import asyncioasync def worker(lock, worker_id):print(f"Worker {worker_id} waiting for the lock")async with lock:print(f"Worker {worker_id} has the lock")await asyncio.sleep(1)print(f"Worker {worker_id} released the lock")async def main():# 创建一个锁lock = asyncio.Lock()# 创建并运行三个工作协程tasks = [asyncio.create_task(worker(lock, i)) for i in range(3)]await asyncio.gather(*tasks)# 运行主协程
asyncio.run(main())
```## 3.2 异步网络请求`aiohttp` 是一个支持 `asyncio` 的异步HTTP网络库。```python
import aiohttp
import asyncioasync def fetch(session, url):async with session.get(url) as response:return await response.text()async def main():async with aiohttp.ClientSession() as session:html = await fetch(session, 'http://python.org')print(html)# 运行主协程
asyncio.run(main())
```## 3.3 异步文件操作`asyncio` 允许你以异步方式执行文件操作。```python
import asyncio
import aiofilesasync def write_to_file(filename, content):async with aiofiles.open(filename, 'w') as f:await f.write(content)async def main():await write_to_file('example.txt', 'Hello, world!')# 运行主协程
asyncio.run(main())
```## 3.4 异步数据库操作对于数据库操作,可以使用像 `aiomysql` 或 `aiopg` 这样的异步驱动。以下是使用 `aiomysql` 的简单示例:```python
import asyncio
import aiomysqlasync def query_db(loop, dbname, user, password):async with aiomysql.create_pool(host='127.0.0.1', port=3306,user=user, password=password,db=dbname, loop=loop) as pool:async with pool.acquire() as conn:async with conn.cursor() as cur:await cur.execute("SELECT 1")result = await cur.fetchone()print(result)loop = asyncio.get_event_loop()
loop.run_until_complete(query_db(loop, 'test', 'user', 'password'))
```## 3.5 异步队列`asyncio` 提供了 `asyncio.Queue`,这是一个异步的先进先出(FIFO)队列。```python
import asyncioasync def worker(q):while True:item = await q.get()print(f'Worker got item: {item}')# 模拟处理项目await asyncio.sleep(1)q.task_done()async def main():q = asyncio.Queue(maxsize=3)# 启动三个工作协程tasks = []for i in range(3):task = asyncio.create_task(worker(q))tasks.append(task)# 生产项目for item in range(10):await q.put(item)# 等待队列清空await q.join()# 取消工作协程for task in tasks:task.cancel()await asyncio.gather(*tasks, return_exceptions=True)# 运行主协程
asyncio.run(main())
```请注意,以上示例代码遵循了代码规范,并包含了必要的注释,以方便理解。2024-12-12 15:41:09.514 | WARNING  | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4 not found in TOKEN_COSTS.
2024-12-12 15:41:09.515 | INFO     | __main__:_act:75 - # 三、Asyncio高级应用## 3.1 并发执行与同步`asyncio` 是 Python 的一个异步I/O框架,用于编写单线程并发代码,通过异步/等待语法。### 并发执行`asyncio` 允许我们并发地运行多个协程。以下是一个简单的并发执行示例:```python
import asyncioasync def say_after(delay, what):await asyncio.sleep(delay)print(what)async def main():print(f"started at {time.strftime('%X')}")# 创建两个协程对象,不立即运行coroutine1 = say_after(1, 'hello')coroutine2 = say_after(2, 'world')# 等待两个协程并发执行await asyncio.gather(coroutine1, coroutine2)print(f"finished at {time.strftime('%X')}")# 运行主协程
asyncio.run(main())
```### 同步在并发编程中,同步是确保多个任务按预期执行的机制。`asyncio` 提供了 `asyncio.Lock()` 和 `asyncio.Event()` 等同步原语。以下是一个使用 `asyncio.Lock()` 的示例:```python
import asyncioasync def worker(lock, worker_id):print(f"Worker {worker_id} waiting for the lock")async with lock:print(f"Worker {worker_id} has the lock")await asyncio.sleep(1)print(f"Worker {worker_id} released the lock")async def main():# 创建一个锁lock = asyncio.Lock()# 创建并运行三个工作协程tasks = [asyncio.create_task(worker(lock, i)) for i in range(3)]await asyncio.gather(*tasks)# 运行主协程
asyncio.run(main())
```## 3.2 异步网络请求`aiohttp` 是一个支持 `asyncio` 的异步HTTP网络库。```python
import aiohttp
import asyncioasync def fetch(session, url):async with session.get(url) as response:return await response.text()async def main():async with aiohttp.ClientSession() as session:html = await fetch(session, 'http://python.org')print(html)# 运行主协程
asyncio.run(main())
```## 3.3 异步文件操作`asyncio` 允许你以异步方式执行文件操作。```python
import asyncio
import aiofilesasync def write_to_file(filename, content):async with aiofiles.open(filename, 'w') as f:await f.write(content)async def main():await write_to_file('example.txt', 'Hello, world!')# 运行主协程
asyncio.run(main())
```## 3.4 异步数据库操作对于数据库操作,可以使用像 `aiomysql` 或 `aiopg` 这样的异步驱动。以下是使用 `aiomysql` 的简单示例:```python
import asyncio
import aiomysqlasync def query_db(loop, dbname, user, password):async with aiomysql.create_pool(host='127.0.0.1', port=3306,user=user, password=password,db=dbname, loop=loop) as pool:async with pool.acquire() as conn:async with conn.cursor() as cur:await cur.execute("SELECT 1")result = await cur.fetchone()print(result)loop = asyncio.get_event_loop()
loop.run_until_complete(query_db(loop, 'test', 'user', 'password'))
```## 3.5 异步队列`asyncio` 提供了 `asyncio.Queue`,这是一个异步的先进先出(FIFO)队列。```python
import asyncioasync def worker(q):while True:item = await q.get()print(f'Worker got item: {item}')# 模拟处理项目await asyncio.sleep(1)q.task_done()async def main():q = asyncio.Queue(maxsize=3)# 启动三个工作协程tasks = []for i in range(3):task = asyncio.create_task(worker(q))tasks.append(task)# 生产项目for item in range(10):await q.put(item)# 等待队列清空await q.join()# 取消工作协程for task in tasks:task.cancel()await asyncio.gather(*tasks, return_exceptions=True)# 运行主协程
asyncio.run(main())
```请注意,以上示例代码遵循了代码规范,并包含了必要的注释,以方便理解。# 四、常见问题与解决方案## 4.1 协程间通信在Python的`asyncio`中,协程之间的通信通常使用`asyncio.Queue`或者`asyncio.Event`来实现。### 示例:使用`asyncio.Queue````python
import asyncioasync def producer(queue):for i in range(5):print(f"Producing item {i}")await queue.put(i)await queue.put(None)  # 用来标记生产结束async def consumer(queue):while True:item = await queue.get()if item is None:breakprint(f"Consuming item {item}")await asyncio.sleep(1)  # 模拟消费时间queue.task_done()queue = asyncio.Queue()
producer_coro = producer(queue)
consumer_coro = consumer(queue)loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
loop.close()
```## 4.2 异步异常处理在异步编程中,异常处理非常重要。可以使用`try-except`块来捕获和处理异常。### 示例:异步异常处理```python
import asyncioasync def async_function_with_error():raise ValueError("An error occurred")async def main():try:await async_function_with_error()except ValueError as e:print(f"Caught an exception: {e}")loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```## 4.3 性能优化性能优化通常涉及减少协程之间的等待时间,以及减少不必要的上下文切换。- 使用`asyncio.gather`来并发运行多个协程。
- 使用`await`关键字仅在你确实需要等待某个操作完成时。### 示例:并发运行多个协程```python
import asyncioasync def fast_function():await asyncio.sleep(1)async def main():await asyncio.gather(fast_function(),fast_function(),fast_function())loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```## 4.4 兼容性问题由于`asyncio`是Python 3.4+的一部分,如果你需要支持更早的Python版本,可能会遇到兼容性问题。- 使用`asyncio`之前,检查Python版本。
- 使用`pip`安装`asyncio`的第三方包,如`aiolib`,来支持旧版本的Python。确保你的代码在支持的版本范围内运行良好,并且遵循最佳实践来减少兼容性问题。---请注意,以上内容遵循了Markdown的语法规范,并提供了相应的代码示例。代码示例遵循了标准的Python代码规范,并包含了必要的2024-12-12 15:41:28.223 | WARNING  | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4 not found in TOKEN_COSTS.注释。2024-12-12 15:41:28.226 | INFO     | __main__:_act:75 - # 四、常见问题与解决方案## 4.1 协程间通信在Python的`asyncio`中,协程之间的通信通常使用`asyncio.Queue`或者`asyncio.Event`来实现。### 示例:使用`asyncio.Queue````python
import asyncioasync def producer(queue):for i in range(5):print(f"Producing item {i}")await queue.put(i)await queue.put(None)  # 用来标记生产结束async def consumer(queue):while True:item = await queue.get()if item is None:breakprint(f"Consuming item {item}")await asyncio.sleep(1)  # 模拟消费时间queue.task_done()queue = asyncio.Queue()
producer_coro = producer(queue)
consumer_coro = consumer(queue)loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
loop.close()
```## 4.2 异步异常处理在异步编程中,异常处理非常重要。可以使用`try-except`块来捕获和处理异常。### 示例:异步异常处理```python
import asyncioasync def async_function_with_error():raise ValueError("An error occurred")async def main():try:await async_function_with_error()except ValueError as e:print(f"Caught an exception: {e}")loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```## 4.3 性能优化性能优化通常涉及减少协程之间的等待时间,以及减少不必要的上下文切换。- 使用`asyncio.gather`来并发运行多个协程。
- 使用`await`关键字仅在你确实需要等待某个操作完成时。### 示例:并发运行多个协程```python
import asyncioasync def fast_function():await asyncio.sleep(1)async def main():await asyncio.gather(fast_function(),fast_function(),fast_function())loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```## 4.4 兼容性问题由于`asyncio`是Python 3.4+的一部分,如果你需要支持更早的Python版本,可能会遇到兼容性问题。- 使用`asyncio`之前,检查Python版本。
- 使用`pip`安装`asyncio`的第三方包,如`aiolib`,来支持旧版本的Python。确保你的代码在支持的版本范围内运行良好,并且遵循最佳实践来减少兼容性问题。---请注意,以上内容遵循了Markdown的语法规范,并提供了相应的代码示例。代码示例遵循了标准的Python代码规范,并包含了必要的注释。# 五、实战案例## 5.1 异步爬虫异步IO在爬虫领域有广泛的应用,因为它可以显著提高爬取效率,特别是在处理网络请求时。以下是一个使用`asyncio`和`aiohttp`的异步爬虫示例。```python
import asyncio
import aiohttpasync def fetch(session, url):async with session.get(url) as response:return await response.text()async def main():async with aiohttp.ClientSession() as session:url = 'http://example.com'html = await fetch(session, url)print(html)if __name__ == '__main__':asyncio.run(main())
```在这个示例中,`fetch` 函数是一个异步的HTTP请求处理函数,它使用了`aiohttp`库来异步获取网页内容。`main` 函数初始化了一个`aiohttp.ClientSession`,然后调用`fetch`函数,并打印出获取的HTML内容。## 5.2 异步Web服务`asyncio`也可以用于创建异步的Web服务。下面是一个使用`aiohttp`创建的简单异步Web服务示例。```python
from aiohttp import webasync def handle(request):name = request.match_info.get('name', "Anonymous")text = f"Hello, {name}!"return web.Response(text=text)app = web.Application()
app.add_routes([web.get('/', handle),web.get('/{name}', handle)
])web.run_app(app)
```在这个例子中,我们创建了一个简单的Web应用程序,它响应根URL和带名字的路径。`handle` 函数是一个异步处理函数,它根据URL路径中的名字返回响应。## 5.3 异步数据处理在数据处理任务中,如果任务可以并行处理,`asyncio`也能提供帮助。以下是一个使用`asyncio`进行异步文件读写的例子。```python
import asyncio
import aiofilesasync def write_data(file_path, data):async with aiofiles.open(file_path, 'w') as f:await f.write(data)async def read_data(file_path):async with aiofiles.open(file_path, 'r') as f:data = await f.read()print(data)async def main():file_path = 'example.txt'data_to_write = '异步文件写入示例'# 写入数据await write_data(file_path, data_to_write)# 读取数据await read_data(file_path)if __name__ == '__main__':asyncio.run(main())
```在这个例子中,`write_data` 函数异步地将数据写入文件,而`read_data` 函数从文件异步读取数据。通过这种方式,可以在处理I/O密集型任务时提高效率。2024-12-12 15:41:46.964 | WARNING  | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4 not found in TOKEN_COSTS.
2024-12-12 15:41:46.965 | INFO     | __main__:_act:75 - # 五、实战案例## 5.1 异步爬虫异步IO在爬虫领域有广泛的应用,因为它可以显著提高爬取效率,特别是在处理网络请求时。以下是一个使用`asyncio`和`aiohttp`的异步爬虫示例。```python
import asyncio
import aiohttpasync def fetch(session, url):async with session.get(url) as response:return await response.text()async def main():async with aiohttp.ClientSession() as session:url = 'http://example.com'html = await fetch(session, url)print(html)if __name__ == '__main__':asyncio.run(main())
```在这个示例中,`fetch` 函数是一个异步的HTTP请求处理函数,它使用了`aiohttp`库来异步获取网页内容。`main` 函数初始化了一个`aiohttp.ClientSession`,然后调用`fetch`函数,并打印出获取的HTML内容。## 5.2 异步Web服务`asyncio`也可以用于创建异步的Web服务。下面是一个使用`aiohttp`创建的简单异步Web服务示例。```python
from aiohttp import webasync def handle(request):name = request.match_info.get('name', "Anonymous")text = f"Hello, {name}!"return web.Response(text=text)app = web.Application()
app.add_routes([web.get('/', handle),web.get('/{name}', handle)
])web.run_app(app)
```在这个例子中,我们创建了一个简单的Web应用程序,它响应根URL和带名字的路径。`handle` 函数是一个异步处理函数,它根据URL路径中的名字返回响应。## 5.3 异步数据处理在数据处理任务中,如果任务可以并行处理,`asyncio`也能提供帮助。以下是一个使用`asyncio`进行异步文件读写的例子。```python
import asyncio
import aiofilesasync def write_data(file_path, data):async with aiofiles.open(file_path, 'w') as f:await f.write(data)async def read_data(file_path):async with aiofiles.open(file_path, 'r') as f:data = await f.read()print(data)async def main():file_path = 'example.txt'data_to_write = '异步文件写入示例'# 写入数据await write_data(file_path, data_to_write)# 读取数据await read_data(file_path)if __name__ == '__main__':asyncio.run(main())
```在这个例子中,`write_data` 函数异步地将数据写入文件,而`read_data` 函数从文件异步读取数据。通过这种方式,可以在处理I/O密集型任务时提高效率。# 六、附录## 6.1 常用库与资源Python 的 `asyncio` 是一个用于编写并发代码的库,使用async/await语法。以下是一些常用的库和资源,可以帮助你更好地理解和应用 `asyncio`。### 常用库- `aiohttp`:用于异步HTTP网络请求。
- `aiomysql` / `aiopg`:用于异步操作MySQL和PostgreSQL数据库。
- `aioredis`:用于异步操作Redis。
- `aiofiles`:用于异步文件操作。### 资源- [官方文档](https://docs.python.org/3/library/asyncio.html):提供了最权威的 `asyncio` 使用指南。
- [Asyncio GitHub 仓库](https://github.com/python/asyncio):可以找到最新的信息和一些示例。## 6.2 最佳实践在使用 `asyncio` 进行编程时,以下是一些最佳实践:1. **避免阻塞操作**:确保你的异步函数不会进行阻塞操作,如长时间的计算或等待输入/输出。
2. **合理使用并发**:不要盲目地创建大量协程,合理地管理和调度它们可以避免资源浪费和提高效率。
3. **错误处理**:使用 `try-except` 块来处理可能出现的异常,确保程序的健壮性。### 代码示例```python
import asyncioasync def fetch_data(url):async with aiohttp.ClientSession() as session:async with session.get(url) as response:return await response.text()async def main():urls = ['http://example.com', 'http://example.org']tasks = [fetch_data(url) for url in urls]results = await asyncio.gather(*tasks)for result in results:print(result)if __name__ == '__main__':asyncio.run(main())
```## 6.3 进一步学习想要进一步学习 `asyncio`,以下是一些建议:- **理解事件循环**:深入了解 `asyncio` 的事件循环是如何工作的,这是 `asyncio` 的核心概念。
- **并发模型**:研究 `asyncio` 的并发模型,包括协程、任务和未来。
- **性能调优**:学习如何对基于 `asyncio` 的应用进行性能分析和调优。通过这些资源的帮助,你可以更深入地掌握 `asyncio`,并在实践中更有效地2024-12-12 15:42:04.027 | WARNING  | metagpt.utils.cost_manager:update_cost:49 - Model GLM-4 not found in TOKEN_COSTS.使用它。2024-12-12 15:42:04.030 | INFO     | __main__:_act:75 - # 六、附录## 6.1 常用库与资源Python 的 `asyncio` 是一个用于编写并发代码的库,使用async/await语法。以下是一些常用的库和资源,可以帮助你更好地理解和应用 `asyncio`。### 常用库- `aiohttp`:用于异步HTTP网络请求。
- `aiomysql` / `aiopg`:用于异步操作MySQL和PostgreSQL数据库。
- `aioredis`:用于异步操作Redis。
- `aiofiles`:用于异步文件操作。### 资源- [官方文档](https://docs.python.org/3/library/asyncio.html):提供了最权威的 `asyncio` 使用指南。
- [Asyncio GitHub 仓库](https://github.com/python/asyncio):可以找到最新的信息和一些示例。## 6.2 最佳实践在使用 `asyncio` 进行编程时,以下是一些最佳实践:1. **避免阻塞操作**:确保你的异步函数不会进行阻塞操作,如长时间的计算或等待输入/输出。
2. **合理使用并发**:不要盲目地创建大量协程,合理地管理和调度它们可以避免资源浪费和提高效率。
3. **错误处理**:使用 `try-except` 块来处理可能出现的异常,确保程序的健壮性。### 代码示例```python
import asyncioasync def fetch_data(url):async with aiohttp.ClientSession() as session:async with session.get(url) as response:return await response.text()async def main():urls = ['http://example.com', 'http://example.org']tasks = [fetch_data(url) for url in urls]results = await asyncio.gather(*tasks)for result in results:print(result)if __name__ == '__main__':asyncio.run(main())
```## 6.3 进一步学习想要进一步学习 `asyncio`,以下是一些建议:- **理解事件循环**:深入了解 `asyncio` 的事件循环是如何工作的,这是 `asyncio` 的核心概念。
- **并发模型**:研究 `asyncio` 的并发模型,包括协程、任务和未来。
- **性能调优**:学习如何对基于 `asyncio` 的应用进行性能分析和调优。通过这些资源的帮助,你可以更深入地掌握 `asyncio`,并在实践中更有效地使用它。

参考链接:https://github.com/geekan/MetaGPT
如果有任何问题,欢迎在评论区提问。

相关文章:

MetaGPT中的教程助手:TutorialAssistant

1. 提示词 COMMON_PROMPT """ You are now a seasoned technical professional in the field of the internet. We need you to write a technical tutorial with the topic "{topic}". """DIRECTORY_PROMPT (COMMON_PROMPT "…...

如何将Python程序打包发布,实现一键安装

哈喽,大家好,我是木头左! 编写完Python脚本后,如何将其高效地发布并安装到其他计算机上,。本文将详细介绍如何将Python程序打包发布,实现一键安装,让程序的分发与部署变得轻松便捷。 一、准备工作 1. 编写和测试程序 在开始打包之前,首先要确保你的Python程序已经编…...

Java 接口

1. 接口概述 (1) Java提供了一个关键字 interface,用这个关键字可以定义接口; (2)格式: public interface 接口名{ //成员变量(常量) //成员方法(抽象方法) } public interface A {//成员变量(接口默认为常量-public static final)String NA…...

RTMP推流平台EasyDSS在无人机推流直播安防监控中的创新应用

无人机与低空经济的关系密切,并且正在快速发展。2024年中国低空经济行业市场规模达到5800亿元,其中低空制造产业占整个低空经济产业的88%。预计未来五年复合增速将达到16.03%。 随着科技的飞速发展,公共安防关乎每一个市民的生命财产安全。在…...

【Flutter_Web】Flutter编译Web第一篇(插件篇):Flutter_web实现上传TOS上传资源,编写web插件

前言 由于Flutter在双端的开发体验几乎接近的情况下,尝试将Flutter代码转Web端进行部署和发布,在其中遇到的所有问题,我都会通过这种方式分享出来。那么第一个要解决的就是上传资源到TOS上,在双端中都是通过插件的方式在各端通过…...

SpringBoot 项目使用 EasyExcel 插件构建 Excel 表格格式(行高、列宽和字体等)工具类

本文主要讲了如何使用 EasyExcel 插件&#xff0c;在导出 Excel 时&#xff0c;设置行高&#xff0c;列宽&#xff0c;表头格式&#xff0c;内容字体大小等工具类。 1、代码使用的依赖 <dependency><groupId>com.alibaba</groupId><artifactId>easyex…...

数据优化带来的问题

原因大概可以猜到 等待进一步深究&#xff08;必须一个是浮点型&#xff09; double x 1 / 2;double x2 static_cast<double> (1 / 2);double x3 (double)1 / (double)2;double x4 (double)1 / 2;double x5 1 / (double)2;double nTotalDataCount 78182;double n…...

2024153读书笔记|《春烂漫:新平摄影作品选》——跳绳酷似人生路,起落平常,进退平常,莫惧征途万里长

2024153读书笔记|《春烂漫&#xff1a;新平摄影作品选》——跳绳酷似人生路&#xff0c;起落平常&#xff0c;进退平常&#xff0c;莫惧征途万里长 《春烂漫&#xff1a;新平摄影作品选》作者新平&#xff0c;2019.12.25年读完的小书&#xff0c;当时就觉得挺不错&#xff0c;今…...

RabbitMQ个人理解与基本使用

目录 一. 作用&#xff1a; 二. RabbitMQ的5中队列模式&#xff1a; 1. 简单模式 2. Work模式 3. 发布/订阅模式 4. 路由模式 5. 主题模式 三. 消息持久化&#xff1a; 消息过期时间 ACK应答 四. 同步接收和异步接收&#xff1a; 应用场景 五. 基本使用 &#xff…...

每天40分玩转Django:Django视图和URL

Django视图和URL 一、课程概述 学习项目具体内容预计用时视图基础函数视图、类视图、视图装饰器90分钟URL配置URL模式、路由系统、命名URL60分钟请求处理请求对象、响应对象、中间件90分钟 二、视图基础 2.1 函数视图 # blog/views.py from django.shortcuts import render…...

ModbusTcp获取数据

ModbusTcp获取数据 记录一个用 pymodbus 库来获取数据的代码。 注意&#xff1a; 1.读取寄存器地址是16进制的。2.大小端转换通过代码知道原理。读取数据时&#xff0c;切记频率别太高&#xff0c;否则会出现连接被关闭问题。 from pymodbus.client.sync import ModbusTcpCli…...

汽车车牌识别数据集,支持YOLO,COCO,VOC格式的标注,8493张图片,可识别多种环境下的车牌

汽车车牌识别数据集&#xff0c;支持YOLO&#xff0c;COCO&#xff0c;VOC格式的标注&#xff0c;8493张图片&#xff0c;可识别多种环境下的车牌 数据集分割 训练组82&#xff05; 6994图片 有效集12&#xff05; 999图片 测试集6% 500图片 预处理 自动…...

YOLOv5+pyqt5+摄像头在特定条件下进行目标检测并采集原始数据

项目介绍 项目地址 GitHub - biabu0/Yolov5_D435i: 通过YOLOV5与pyqt5实现一个使用D435i深度摄像头采集特定需求与场景下的深度数据的小程序 通过YOLOV5对指定的区域进行检测&#xff0c;当检测到目标进入特定区域时&#xff0c;开始保存数据&#xff0c;摄像头采用D435i深度…...

代码随想录-算法训练营-番外(图论02:岛屿数量,岛屿的最大面积)

day02 图论part02 今日任务:岛屿数量,岛屿的最大面积 都是一个模子套出来的 https://programmercarl.com/kamacoder/0099.岛屿的数量深搜.html#思路往日任务: day01 图论part01 今日任务:图论理论基础/所有可到达的路径 代码随想录图论视频部分还没更新 https://programmercar…...

C# 23种设计模式(3)工厂(SimpleFactory)模式

一、工厂模式介绍 工厂模式&#xff08;Factory Pattern&#xff09;是一种在软件开发中常用的创建型设计模式。它的主要目的是将对象的创建逻辑与使用逻辑分离&#xff0c;使得增加新的对象类型时不需要修改使用对象的代码。这样做提高了系统的可扩展性和可维护性。 工厂模式…...

安卓主板_MTK联发科android主板方案

在当前智能设备的发展中&#xff0c;安卓主板的配置灵活性和性能优化显得尤为重要。安卓主板的联发科方案&#xff0c;在芯片上&#xff0c;搭载联发科MTK6761、MT8766、MT6765、MT6762、MT8768、MT8390、MTK8370以及MT8788等型号&#xff0c;均基于64位的四核或八核架构设计。…...

中企出海 - 平行账 - Parallel Ledger

以中国企业出海美国&#xff0c;为同时满足中国和美国的会计核算要求&#xff0c;请给出SAP 平行账的实施方案及国家科目表(alternative account)实施海外国家的注意事项 中国企业在美国开展业务需同时满足中国和美国的会计准则&#xff0c;这通常包括《中国企业会计准则》&am…...

Pyside6 --Qt设计师--简单了解各个控件的作用之:Item Views

目录 一、List View二、Tree View三、Table View四、Column View 一、List View 学习方法和Buttons一样&#xff0c;大家自己在qt设计师上面在属性编辑区进行相应的学习&#xff01; 我就先紧着qt设计师的页面进行讲解&#xff0c;部分内容查自AI。 后面有什么好用的控件或者…...

智能家居WTR096-16S录放音芯片方案,实现语音播报提示及录音留言功能

前言&#xff1a; 在当今社会的高速运转之下&#xff0c;夜幕低垂之时&#xff0c;许多辛勤工作的父母尚未归家。对于肩负家庭责任的他们而言&#xff0c;确保孩童按时用餐与居家安全成为心头大事。此时&#xff0c;家居留言录音提示功能应运而生&#xff0c;恰似家中的一位无形…...

算法2(蓝桥杯19)-合并两个有序链表

问题&#xff1a;将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 解题思路&#xff1a; 创建一个虚拟节点&#xff0c;循环比较l1、l2链表各节点的大小&#xff0c;将较小的节点追加到虚拟节点后&#xff0c;返回新链表 1、…...

OpenAI 正式赋予 ChatGPT 通过视频实时与用户互动的能力

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…...

【Email】基于SpringBoot3.4.x集成发送邮件功能

【Email】基于SpringBoot3.4.x集成发送邮件功能 摘要本地开发环境说明pom.xml启动类application.yaml写一个邮件模板定义模板引擎工具类定义一个邮件发送对象封装一个邮件发送器单元测试邮件模板单元测试发送邮件单元测试 邮件效果参考资料 摘要 在业务系统开发过程中&#xf…...

debian12学习笔记

前置条件 基于debian12官网的qcow2格式文件进行操作 安装ssh 登录虚拟机后安装ssh服务端 apt install openssh-server配置国内源 新增/etc/apt/sources.list.d/tsinghua.list 使用清华大学的源 https://www.cnblogs.com/shanhubei/p/18104430 deb https://mirrors.tuna.t…...

(补)算法刷题Day16:BM39 序列化二叉树

题目链接 描述 思路&#xff1a; 自行序列化和反序列化。元素用逗号分隔。 序列化&#xff1a; 使用队列层序遍历。遍历每一层节点&#xff0c;并访问其左右孩子&#xff0c;如果是空则序列化成#&#xff0c;如果是数字&#xff0c;则序列化成str。 反序列化&#xff1a; 使…...

科研绘图系列:R语言绘制热图和散点图以及箱线图(pheatmap, scatterplot boxplot)

禁止商业或二改转载,仅供自学使用,侵权必究,如需截取部分内容请后台联系作者! 文章目录 介绍加载R包数据下载图1图2图3系统信息参考介绍 R语言绘制热图和散点图以及箱线图(pheatmap, scatterplot & boxplot) 加载R包 library(magrittr) library(dplyr) library(ve…...

docker 安装mysql 5.7 详细保姆级教程

1. 安装mysql(5.7) docker pull mysql:5.7 若是拉取不了&#xff0c;可以配置下 docker 源 2. 查看是否安装成功 docker images 下图就是成功了 3.创建mysql专用目录、数据挂载目录、配置文件目录 &#xff0c;演示目录在于/home/下 //命令逐条执行cd /home/ mkdir mysql …...

PostgreSql

PostgreSql 1.物化视图1.1 创建物化视图1.2 查询物化视图1.3 使用物化视图1.4 刷新物化视图1.5 删除物化视图 1.物化视图 物化视图是一种存储查询结果的数据库对象。与普通视图不同&#xff0c;物化视图将查询结果实际存储在磁盘上&#xff0c;而不是在每次查询时动态计算结果…...

优化移动端H5:常见问题与解决方案

移动端H5开发中的“坑”与解决方案 本文介绍了开发中遇到的几个关于移动端H5开发中的小问题&#xff0c;以及解决的方法。 一、iOS滑动不流畅问题 在iOS设备上&#xff0c;H5页面的滑动效果有时会出现不流畅的情况&#xff0c;特别是在页面高度超过一屏时。这通常是由于iOS的…...

AWS Glue实现RDS到RDS的数据同步

使用 在AWS上,AWS Glue 是一个完全托管的ETL(Extract, Transform, Load)服务,可以轻松地将数据从一个源系统提取出来,转换数据格式,然后将其加载到目标系统。本文将详细介绍如何使用AWS Glue将数据从一个RDS(关系型数据库服务)实例同步到另一个RDS实例,而无需手动编写…...

【Redis】Redis缓存击穿

1. 概述 缓存击穿&#xff1a;缓存击穿问题也叫热点key问题&#xff0c;一个高并发的key或重建缓存耗时长&#xff08;复杂&#xff09;的key失效了&#xff0c;此时大量的请求给数据库造成巨大的压力。如下图&#xff0c;线程1还在构建缓存时&#xff0c;线程2&#xff0c;3&…...

QILSTE H8-316QFO高亮橙光LED灯珠 发光二极管LED

在当今电子技术领域&#xff0c;H8-316QFO型号的LED以其卓越的性能和可靠性 脱颖而出。本文将深入探讨这款LED的关键参数&#xff0c;以期为工程师和技术人员提供详尽的技术参考。 首先&#xff0c;H8-316QFO的物理特性不容忽视。其外观尺寸为3.2x1.5x0.8mm&#xff0c;小巧的…...

pytest入门三:setup、teardown

https://zhuanlan.zhihu.com/p/623447031 function对应类外的函数&#xff0c;每个函数调用一次 import pytest def setup_module():print(开始 module)def teardown_module():print(结束 module)def setup_function():print(开始 function)def teardown_function():print(结…...

MySQL有哪些高可用方案?

大家好&#xff0c;我是锋哥。今天分享关于【MySQL有哪些高可用方案?】面试题。希望对大家有帮助&#xff1b; MySQL有哪些高可用方案? 1000道 互联网大厂Java工程师 精选面试题-Java资源分享网 MySQL 高可用方案旨在确保数据库系统的高可靠性、低宕机时间、以及在硬件故障…...

IT 行业的就业情况

当前&#xff0c;IT 行业的就业情况呈现出以下特点&#xff1a; 1. 需求持续增长&#xff1a;随着数字化转型的加速&#xff0c;各个行业对信息技术的依赖程度不断提高&#xff0c;推动了对 IT 人才的持续需求。特别是在云计算、大数据、人工智能、物联网等新兴领域&#xff…...

[SWPU 2019]漂流记的马里奥

[SWPU 2019]漂流记的马里奥 解压安装包&#xff0c;里面有一个exe程序&#xff0c;运行后得到一个1.txt的文件 打开1.txt文件发现里面有给flag.txt 在这里的话可以用windows中的命令来打开falg.txt文件 notepad是一个用于打开Windows系统自带的记事本程序的命令 输入 notepa…...

如何在Android设备上复制整个目录到另一个位置?

在Android设备上复制整个目录到另一个位置&#xff0c;通常需要通过adb工具&#xff08;Android Debug Bridge&#xff09;来进行操作&#xff0c;因为它提供了文件系统级别的访问权限。以下是步骤&#xff1a; 打开命令行终端&#xff1a;首先&#xff0c;你需要连接你的Andro…...

人工智能在医疗健康领域的革命:从早期诊断到个性化治疗

引言&#xff1a;人工智能如何改变医疗健康 人工智能&#xff08;AI&#xff09;正在以惊人的速度渗透到医疗健康领域&#xff0c;从自动化诊断到个性化治疗&#xff0c;AI技术为提高医疗服务效率、降低成本和提升治疗效果提供了革命性的解决方案。本文将探讨人工智能在医疗健…...

MPQ3364调试异常异常问题

问题 MPQ3364_FAULT脚不报异常&#xff1f; 分析思路 首先排除硬件环境 1)把BL PWM接到3.3V&#xff08;相当于PWM100%&#xff09;&#xff0c;FAULT脚和MCU断开&#xff0c;拔掉屏幕&#xff0c;FAULT 可以报异常 2.保持相同的输入环境&#xff0c;测试差异&#xff1a; 软…...

Flutter中GetBuilder 和 GetX 的区别

在 GetX 框架中&#xff0c;GetBuilder 和 GetX 都是用来构建响应式 UI 的&#xff0c;但它们在使用方式和适用场景上有一些不同。 GetBuilder 作用: 用于监听控制器中的特定变量变化并重新构建部分 UI。 特点: 只有当 update() 方法被调用时&#xff0c;才会触发 UI 的重建。…...

vue2+element-ui实现多行行内表格编辑

效果图展示 当在表格中点击编辑按钮时:点击的行变成文本框且数据回显可以点击确定按钮修改数据或者取消修改回退数据: 具体实现步骤 1. 行数据定义编辑标记 行数据定义编辑标记 当在组件中获取到用于表格展示数据的方法中,针对每一行数据添加一个编辑标记 this.list.f…...

Vue3+TypeScript+AntVX6实现Web组态(从技术层面与实现层面进行分析)内含实际案例教学

摘要 用Vue3+TypeScript+AntVX6实现Web组态(从技术层面与实现层面进行分析),包含画布创建、节点设计、拖拽实现(实际案例)、节点连线、交互功能,后续文章持续更新。 注:本文章可以根据目录进行导航 文档支持 AntVX6使用文档 https://x6.antv.antgroup.com/tutorial…...

【卷积神经网络】LeNet实践

模型建立 数据初始化根据模型搭建前向传播打印模型结构 前向传播数据初始化 def __init__(self):super(LeNet, self).__init__()# 第一层卷积层&#xff1a;# 输入&#xff1a;灰度图像 (1通道&#xff0c;大小 28x28)# 输出&#xff1a;6个特征图 (大小 28x28, 通过padding2保…...

FPGA实现GTP光口数据回环传输,基于Aurora 8b/10b编解码架构,提供2套工程源码和技术支持

目录 1、前言工程概述免责声明 2、相关方案推荐我已有的所有工程源码总目录----方便你快速找到自己喜欢的项目我这里已有的 GT 高速接口解决方案 3、工程详细设计方案工程设计原理框图用户数据发送模块基于GTP高速接口的数据回环传输架构GTP IP 简介GTP 基本结构GTP 发送和接收…...

Tongweb8命令行使用收集(by lqw)

文章目录 声明对应版本修改thanos用户密码部署应用到默认实例节点相关操作新增节点(一般一个服务器ip只能装一个节点)启动节点(需确认节点没有运行)停止节点删除节点节点新增应用节点查看应用节点启动应用节点停止应用节点卸载应用(谨慎操作,卸载后应用就没有了,建议备份后…...

基于STM32的火灾烟雾报警器设计开题报告

开题报告 题目&#xff1a;基于STM32的火灾烟雾报警器Proteus仿真设计 一、研究背景与意义 随着现代城市化进程的加快&#xff0c;火灾安全问题日益凸显&#xff0c;火灾的早期预警对于减少人员伤亡和财产损失至关重要。传统的火灾报警系统往往依赖于烟雾或温度的单一检测&a…...

go 语言zero项目设置后台运行的几种方式

在 Go 项目中将程序设置为后台运行通常有几种方法。你可以使用 systemd、nohup 或者将 Go 程序作为服务启动。以下是几种常见的方法&#xff0c;分别适用于不同的场景。 ### 1. 使用 nohup 命令将 Go 程序后台运行 nohup 是一个常用的 Linux 工具&#xff0c;它可以将命令行程…...

数据库中的代数运算

这些代数基本运算通常被封装在数据库查询语言中&#xff0c;如SQL中的SELECT、FROM、WHERE等子句&#xff0c;使得用户可以更方便地对数据库进行查询和处理。 下面的介绍基于以下两个关系来说明&#xff1a; 传统的集合运算 并&#xff08;∪&#xff09; 合并两个关系中的元组…...

【机器学习】机器学习的基本分类-无监督学习-核密度估计(Kernel Density Estimation, KDE)

核密度估计&#xff08;Kernel Density Estimation, KDE&#xff09; 核密度估计&#xff08;KDE&#xff09;是一种非参数化方法&#xff0c;用于估计数据的概率密度函数&#xff08;PDF&#xff09;。与直方图相比&#xff0c;KDE 能够生成平滑的概率密度曲线&#xff0c;是…...

语义分割——DeeplabV3plus

DeeplabV3plus 是一种先进的用于语义分割任务的深度学习模型。DeepLabV3plus模型采用了编码器-解码器&#xff08;Encoder-Decoder&#xff09;结构&#xff0c;通过编码器提取图像特征&#xff0c;再通过解码器将这些特征映射回原始图像尺寸&#xff0c;实现像素级的分类。具体…...

【Leetcode 每日一题 - 扩展】50. Pow(x, n)

问题背景 实现 p o w ( x , n ) pow(x, n) pow(x,n)&#xff0c;即计算 x x x 的整数 n n n 次幂函数&#xff08;即&#xff0c; x n x_n xn​&#xff09;。 数据约束 − 100.0 < x < 100.0 -100.0 \lt x \lt 100.0 −100.0<x<100.0 − 2 31 ≤ n ≤ 2 31 −…...