什么是 pdoc?
pdoc 是一个用于为 Python 项目自动生成文档的工具,支持生成 HTML 或 Markdown 格式,适合快速构建 API 文档。
安装
使用 pip 安装 pdoc:
pip install pdoc
6/29/25Less than 1 minute
pdoc 是一个用于为 Python 项目自动生成文档的工具,支持生成 HTML 或 Markdown 格式,适合快速构建 API 文档。
使用 pip 安装 pdoc:
pip install pdoc
asyncio 是 Python 用于编写并发代码的库。它使用 async/await 语法,使得编写异步程序变得更加直观和简单。asyncio 主要用于 I/O 绑定和高层次结构化网络代码。
以下是一个使用 asyncio 的示例代码,它展示了如何动态添加和管理异步任务。
import asyncio
import sys
import time
stop_event = asyncio.Event()
async def func(name):
i = 0
while not stop_event.is_set():
print(f"{name} : {i}")
i += 1
await asyncio.sleep(1)
async def append_task(name):
task = asyncio.create_task(func(name))
return task
async def listen_for_input():
reader = asyncio.StreamReader()
protocol = asyncio.StreamReaderProtocol(reader)
await asyncio.get_running_loop().connect_read_pipe(lambda: protocol, sys.stdin)
while not stop_event.is_set():
input_line = await reader.readline()
input_line = input_line.decode().strip()
if input_line.lower() == "stop":
stop_event.set()
else:
task = await append_task(input_line)
task_list.append(task)
async def main():
start_time = time.time()
global task_list
task_list = []
input_task = asyncio.create_task(listen_for_input())
# 使用事件循环持续运行,支持动态添加任务
# while not stop_event.is_set():
# await asyncio.sleep(0.1)
await stop_event.wait()
await input_task
await asyncio.gather(*task_list)
end_time = time.time()
print(f"Total run time: {end_time - start_time} seconds")
if __name__ == "__main__":
asyncio.run(main())
functools.wraps 是 Python 中的一个装饰器,用于装饰另一个装饰器,使其保留被装饰函数的元数据,如函数名、文档字符串等。这在编写装饰器时非常有用,因为装饰器会改变被装饰函数的属性,使得调试和文档生成变得困难。
以下是一个没有使用 functools.wraps 的装饰器示例:
def my_decorator(func):
def wrapper(*args, **kwargs):
"""decorator"""
print('Calling decorated function...')
return func(*args, **kwargs)
return wrapper
@my_decorator
def example():
"""Docstring"""
print('Called example function')
print(example.__name__, example.__doc__)
Python 中两个模块互相 import 会导致 ImportError 或部分加载后的 AttributeError。这类问题在项目变大后很难排查,尤其是间接的循环依赖(A → B → C → A)。
Python 项目通常用 requirements.txt 管理依赖。但生成这个文件的方式有讲究,用错了可能引入本地路径,导致其他环境无法安装。
原文转载自「刘悦的技术博客」https://v3u.cn/a_id_208