首页 文章 精选 留言 我的

精选列表

搜索[Token效率],共10000篇文章
优秀的个人博客,低调大师

6步优化脚本效率

采集脚本接入代理后失败率不降反升,是个很常见的现象。原因通常不是代理质量差,而是脚本缺少"识别失败类型 → 判断处理动作 → 针对性重试"这条闭环。本文按改造顺序拆成六步,每一步给出可运行代码,并说明它消除的是哪一类无效请求。 --- ## **环境与前提** 代码在以下环境验证: - Python 3.11、requests 2.31、aiohttp 3.9、urllib3 2.x - 目标端:自建静态站点(用于可控压测)+ 若干公开数据接口 - 代理:极安代理,测试中用到两种接入形态 - 短效代理:单 IP 存活 1–15 分钟(五档可选),到期自动失效 - 隧道代理:脚本侧固定一个入口地址,出口 IP 由服务端轮换 后文第 4 步的 Session 复用粒度、第 6 步的冷却期取值,都是从上面这两个参数推出来的。换成其他供应商时,需要按各自的 IP 存活时长和接入方式重新标定这两个数——这也是本文把环境写在前面的原因。 **合规提醒**:以下方法只适用于公开数据采集。执行前请确认目标站点的 `robots.txt` 与服务条款,遵守其中声明的 `Crawl-delay`,不采集个人信息、不绕过登录态与付费墙、不对目标造成可感知的负载压力。 --- ## **0. 先把失败分类,再谈优化** 绝大多数"优化"失败,是因为改造前后只有一个总失败率数字,无法判断哪一步起了作用。所以第一件事是打点,把失败拆成可归因的类别。 ``` import threading from collections import Counter import requests class FailureStats: """线程安全的失败分类计数器。""" def __init__(self): self._counter = Counter() self._lock = threading.Lock() def record(self, category: str) -> None: with self._lock: self._counter[category] += 1 def report(self) -> dict: with self._lock: total = sum(self._counter.values()) if not total: return {} return { k: {"count": v, "ratio": round(v / total, 4)} for k, v in self._counter.most_common() } def classify(status: int | None = None, exc: BaseException | None = None) -> str: """把一次请求结果归到一个可决策的类别上。""" if status is not None: if 200 str | None: try: resp = requests.head( PRECHECK_URL, proxies={"http": proxy, "https": proxy}, timeout=(2, 3), allow_redirects=False, ) return proxy if resp.status_code list[str]: with ThreadPoolExecutor(max_workers=workers) as pool: return [p for p in pool.map(precheck, proxy_list) if p] ``` 几个容易踩的点: - 用 `HEAD` 而非 `GET`,只验通路不拉正文; - `allow_redirects=False`,跳转本身不是可用性信号; - 预检不重试。预检里重试等于把"筛选"变成了"抢救",成本会翻倍; - 预检并发别开太高,20 上下即可,否则预检自己会成为瓶颈。 短效 IP 的场景下,预检和提取应该合并成一步:提取后立刻过一遍连通性再入池,中间不要有队列积压,否则 IP 在排队时就已经过期了。 --- ## **2. 超时分层** `timeout=10` 这种写法会把"慢但可用"和"根本连不上"当成同一件事处理。requests 支持二元组,把两者拆开: ``` resp = requests.get( target_url, proxies={"http": proxy, "https": proxy}, timeout=(3, 15), # (connect_timeout, read_timeout) headers=default_headers, ) ``` - **连接超时**:3 秒内建不上连接,基本可以判定这条链路有问题,快速失败换 IP,不必等待; - **读取超时**:15 秒是留给慢链路的窗口,目标站点响应慢和代理不可用是两回事。 经验区间:连接超时 2–5 秒,读取超时 10–20 秒。把 timeout 统一写成 30 秒是常见反模式——坏代理不会被及时淘汰,还会长时间占住 worker,整体吞吐反而更低。 aiohttp 侧对应的写法粒度更细: ``` import aiohttp timeout = aiohttp.ClientTimeout( total=30, sock_connect=3, sock_read=15, ) ``` --- ## **3. 按失败类别分级重试** 不是所有失败都值得重试。403、404 重试一百次结果一样,而 502、连接中断换个 IP 往往就通了。 |类别|动作|最大次数|说明| | --- | --- | --- | --- | |ok|接受|—|记录成功| |target_reject(401/403/451)|跳过|0|目标明确拒绝,换 IP 也无效| |not_found|跳过|0|资源不存在| |rate_limited(429)|延时后重试|1|优先读 Retry-After| |target_5xx|原 IP 短延时重试|2|目标侧故障,与代理无关| |proxy_error / conn_error|换 IP 重试|3|链路问题| |connect_timeout / read_timeout|换 IP 重试|2|代理慢或失联| |ssl_error|换 IP 重试|1|多为中间设备劫持| 落成配置表而不是 if-else 链,后续调参只改数据: ``` import random from enum import Enum class Action(str, Enum): ACCEPT = "accept" SKIP = "skip" RETRY_SAME = "retry_same" RETRY_SWITCH = "retry_switch" DELAY_RETRY = "delay_retry" POLICY: dict[str, tuple[Action, int]] = { "ok": (Action.ACCEPT, 0), "target_reject": (Action.SKIP, 0), "not_found": (Action.SKIP, 0), "rate_limited": (Action.DELAY_RETRY, 1), "target_5xx": (Action.RETRY_SAME, 2), "proxy_error": (Action.RETRY_SWITCH, 3), "conn_error": (Action.RETRY_SWITCH, 3), "connect_timeout": (Action.RETRY_SWITCH, 2), "read_timeout": (Action.RETRY_SWITCH, 2), "ssl_error": (Action.RETRY_SWITCH, 1), "unknown": (Action.RETRY_SWITCH, 1), } def decide(category: str, attempt: int) -> Action: action, max_attempts = POLICY.get(category, (Action.RETRY_SWITCH, 1)) if action in (Action.ACCEPT, Action.SKIP): return action return action if attempt float: """指数退避 + 抖动,避免多协程在同一时刻集中重试。""" exp = min(cap, base * (2 ** attempt)) return exp * (0.5 + random.random() * 0.5) ``` 统一按"失败就重试 3 次"处理的脚本,重试请求里有相当大一部分是打在硬拒绝上的——这些请求全部属于无效请求,且会额外消耗 IP 配额。分级之后,重试预算才会花在真正可能成功的失败上。 429 的处理还有一个细节:优先读响应头里的 `Retry-After`,服务端已经给出了等待时长,自己拍一个 60 秒既可能不够也可能浪费。 ``` def retry_after_seconds(resp, fallback: float = 60.0) -> float: value = resp.headers.get("Retry-After") if not value: return fallback try: return float(value) except ValueError: return fallback # HTTP-date 格式,按需再解析 ``` --- ## **4. Session 与连接池复用** 每次 `requests.get()` 都会新建连接,重复付出 DNS 解析 + TCP 握手 + TLS 握手的成本。代理链路下这段开销更明显,因为握手要多走一跳。 ``` import threading import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry class SessionFactory: """按代理入口地址复用 Session,退池时同步关闭释放连接。""" def __init__(self, pool_connections: int = 10, pool_maxsize: int = 20): self._sessions: dict[str, requests.Session] = {} self._lock = threading.Lock() self._pool_connections = pool_connections self._pool_maxsize = pool_maxsize def _build(self, proxy: str) -> requests.Session: session = requests.Session() session.proxies = {"http": proxy, "https": proxy} adapter = HTTPAdapter( pool_connections=self._pool_connections, pool_maxsize=self._pool_maxsize, # 底层重试全部关掉,重试策略由上层的 POLICY 统一决定, # 否则两套重试会叠乘,实际请求数远超预期。 max_retries=Retry(total=0, backoff_factor=0, status_forcelist=[]), ) session.mount("http://", adapter) session.mount("https://", adapter) return session def get(self, proxy: str) -> requests.Session: with self._lock: if proxy not in self._sessions: self._sessions[proxy] = self._build(proxy) return self._sessions[proxy] def drop(self, proxy: str) -> None: with self._lock: session = self._sessions.pop(proxy, None) if session is not None: session.close() ``` 两个关键点: **一、底层重试必须关掉。** `HTTPAdapter` 默认的 `Retry` 和第 3 步的分级重试是两套独立机制,同时开启时实际请求数是两者相乘,日志上会表现为"明明只配了 3 次重试,抓包却有 9 次"。 **二、退池时要 `close()`。** 只从字典里删掉引用,底层连接池要等 GC 才释放,长跑任务里会看到 socket 数持续上涨。 复用粒度取决于接入形态: - **独立 IP 列表**:Session 按 IP 建,一个 IP 一个池; - **隧道形态**:脚本只固定一个入口地址,出口 IP 由服务端轮换,此时整个进程可以共用一个 Session,握手成本被摊薄到接近零——这是隧道接入在工程上最实际的收益。 --- ## **5. 并发上限约束(附一个高频误用)** 并发不是越高越好。单 IP 对同一目标的并发超过阈值就会触发限速,`rate_limited` 和 `target_5xx` 会同时上升,整体吞吐反而下降。 定档依据: - `robots.txt` 声明了 `Crawl-delay` 的,按声明执行,不做加速; - 无声明的公开数据,单 IP 并发 1–3,总并发随可用 IP 数线性扩展; - 页面重、服务端渲染慢的目标,单 IP 并发压到 1。 **一个非常容易写错的地方**:Semaphore 必须在循环外创建。写成下面这样是无效的—— ``` # ❌ 错误:每个 task 各自持有一个新信号量,等于没有限流 for i, url in enumerate(urls): sem = asyncio.Semaphore(MAX_PER_IP) tasks.append(fetch(sessions[i % len(sessions)], url, sem)) ``` 正确写法是按代理各建一个,并叠加一个全局信号量: ``` import asyncio import aiohttp MAX_PER_IP = 2 MAX_TOTAL = 30 TIMEOUT = aiohttp.ClientTimeout(total=30, sock_connect=3, sock_read=15) async def fetch(session, url, ip_sem, total_sem): async with total_sem, ip_sem: try: async with session.get(url, timeout=TIMEOUT) as resp: if resp.status >= 400: return None, classify(status=resp.status) return await resp.text(), "ok" except asyncio.TimeoutError: return None, "read_timeout" except aiohttp.ClientError as exc: return None, classify(exc=exc) async def run_batch(urls: list[str], sessions: dict[str, aiohttp.ClientSession]): total_sem = asyncio.Semaphore(MAX_TOTAL) ip_sems = {proxy: asyncio.Semaphore(MAX_PER_IP) for proxy in sessions} keys = list(sessions) tasks = [ fetch(sessions[keys[i % len(keys)]], url, ip_sems[keys[i % len(keys)]], total_sem) for i, url in enumerate(urls) ] return await asyncio.gather(*tasks) ``` 并发上限的另一半价值是保护本机。单进程 1000+ 并发时,asyncio 事件循环调度本身会成为新瓶颈,此时提高并发数只会让 P99 延迟继续恶化。 --- ## **6. 失败 IP 退池与冷却** 坏 IP 不退池,会被后续请求反复命中,形成雪崩:失败率上升 → 重试增多 → 又打到同一批坏 IP。 ``` import threading import time from collections import defaultdict class IPPool: def __init__(self, proxies, fail_threshold: int = 3, cooldown: int = 300): self._available = list(proxies) self._failed: dict[str, float] = {} self._fail_count: dict[str, int] = defaultdict(int) self._cursor = 0 self._fail_threshold = fail_threshold self._cooldown = cooldown self._lock = threading.Lock() def acquire(self) -> str | None: """轮询取用,避免总是命中列表头部的同一个 IP。""" with self._lock: self._recover_locked() if not self._available: return None self._cursor = (self._cursor + 1) % len(self._available) return self._available[self._cursor] def mark_success(self, proxy: str) -> None: with self._lock: self._fail_count[proxy] = 0 def mark_fail(self, proxy: str) -> None: with self._lock: self._fail_count[proxy] += 1 if self._fail_count[proxy] >= self._fail_threshold: if proxy in self._available: self._available.remove(proxy) self._cursor = 0 self._failed[proxy] = time.time() def _recover_locked(self) -> None: now = time.time() for proxy, failed_at in list(self._failed.items()): if now - failed_at > self._cooldown: self._failed.pop(proxy) self._fail_count[proxy] = 0 self._available.append(proxy) @property def stats(self) -> dict: with self._lock: return {"available": len(self._available), "cooling": len(self._failed)} ``` 几个设计取舍: - **失败 3 次才退池**,而不是 1 次。单次失败可能来自目标侧抖动,一次就退会误伤大量好 IP; - **`mark_success` 要清零计数**,否则长跑任务里所有 IP 的失败次数只增不减,最终全池退空; - **回收在 `acquire` 时顺带做**,不额外起线程,主流程零等待。 **冷却期怎么定,取决于 IP 的存活时长。** 固定长效 IP 用 300 秒是合理的;但短效场景下 IP 本身只存活 1–15 分钟(极安代理短效代理为五档可选、到期自动失效),冷却 300 秒等于让 IP 在冷却期内直接过期,回收动作没有意义。这类场景应把冷却压到 60 秒以内,重心从"等它恢复"改为"立即换下一个"。隧道形态则不需要 `IPPool` 这一层,退池逻辑由服务端承担,脚本侧只保留失败计数用于告警。 --- ## **整合:一个最小可运行实现** 把六步串起来: ``` import time import requests def fetch_with_policy( url: str, pool: IPPool, factory: SessionFactory, stats: FailureStats, max_rounds: int = 5, ) -> str | None: attempt = 0 proxy = pool.acquire() for _ in range(max_rounds): if proxy is None: stats.record("pool_exhausted") return None session = factory.get(proxy) try: resp = session.get(url, timeout=(3, 15)) category = classify(status=resp.status_code) except requests.RequestException as exc: category = classify(exc=exc) resp = None stats.record(category) if category == "ok": pool.mark_success(proxy) return resp.text action = decide(category, attempt) attempt += 1 if action is Action.SKIP: return None if action is Action.DELAY_RETRY: time.sleep(retry_after_seconds(resp) if resp is not None else 60.0) continue if action is Action.RETRY_SAME: time.sleep(backoff(attempt)) continue if action is Action.RETRY_SWITCH: pool.mark_fail(proxy) factory.drop(proxy) proxy = pool.acquire() time.sleep(backoff(attempt, base=0.5)) continue return None ``` --- ## **改造后还剩多少无效请求?** 把 `FailureStats.report()` 接到日志或监控上,改造前后各跑一轮同样的 URL 集合,对比分布,例如: |失败类别|改造前占比|改造后占比|主要归因| | --- | --- | --- | --- | |proxy_error|高|显著下降|第 1、6 步| |connect_timeout|高|显著下降|第 1、2 步| |rate_limited|中|明显下降|第 5 步| |target_reject 上的重试量|中|归零|第 3 步| |target_5xx|低|基本不变|目标侧因素,不可控| > 具体数值与目标站点、代理形态、IP 数量强相关,建议直接跑自己的基线数据,不要照搬别人的百分比。 无效请求率归零是不可能的:目标站点的瞬时故障、DNS 抖动、路由波动都会产生不可避免的失败。经验上,5% 以内属于良好,10% 以内可接受,持续超过 15% 说明脚本或链路存在需要回查的问题。 --- ## **超标时的回查顺序** 按维度逐层收敛,不要一上来就换代理: 1. **看错误码分布** —— 是否集中在某一两个类别?集中在 `proxy_error` 查链路,集中在 `rate_limited` 查并发,集中在 `target_reject` 查请求指纹(UA、Header 顺序、Cookie); 1. **看时间分布** —— 是否集中在某个时段?可能是目标站点的高峰期或定时策略,也可能是自己的定时任务撞在了一起; 1. **看目标分布** —— 是否集中在某几个 URL 或域名?那多半是目标侧规则变化,与代理无关; 1. **看 IP 分布** —— 是否集中在少数 IP?说明预检强度不够,或退池阈值设得太宽松。 四个维度定位到具体原因后再动手,比盲目调参有效得多。 --- ## **小结** 代理只解决"出口 IP"这一个环节。真正决定无效请求率的,是脚本对失败的处理逻辑:能不能分清失败类型、会不会在无意义的地方重试、坏 IP 能不能及时退出。这六步的顺序也是有意义的——先有度量,再做筛选(1)、控制单次成本(2、4)、约束速率(5),最后才是失败后的处置(3、6)。跳过第 0 步直接改代码,最后往往说不清是哪一步起了作用。

优秀的个人博客,低调大师

PyCharm 2026.2正式发布:默认调试器升级成了这个,效率++

我秘密的爱着你 却没有像他们那样有一定要拥有你的强烈希望 前几天,在PyCharm 2026.2 新版本中,终于将 **debugpy 设为所有 Python 项目默认调试器** ,这个决定可能看起来像是一个不起眼的技术选型变更。但这背后,是 JetBrains 对 Python 调试体验的一次深刻反思和重大升级。 ## 从“可选”到“默认” 其实早在 2026.1 版本中,debugpy 就已作为可选后端引入。而 2026.2 将其设为默认,标志着一个明确的信号:**基于 Debug Adapter Protocol (DAP) 的调试时代已经全面到来。** 在此之前,PyCharm 的调试器经历了长期的发展,但其底层架构与新兴的 Python 语言特性和开发者工具生态之间,逐渐出现了摩擦。debugpy 的崛起,尤其是它被微软选为 Python 在 VS Code 中的官方调试器后,已成为事实上的标准。PyCharm 此次转向,可以看作是对这一生态现实的正式拥抱。 ![](https://developer.qcloudimg.com/http-save/yehe-11859176/0f9717947e5a9a17cb348415b4543d34.png) 调试流程和过去保持不变 ![](https://developer.qcloudimg.com/http-save/yehe-11859176/25b6c3a6f77630dd5cdbea062c0042e2.png) ## 新默认调试器带来的三大核心优势 1. **性能的飞跃,尤其对 Python 3.12+**:debugpy 默认集成了 **PEP 669 低影响监控 API**。这意味着在 Python 3.12 及更高版本中,调试时的性能开销会显著降低。对于拥有大型代码库和频繁调试需求的开发者来说,这能直接提升日常开发的流畅度。 1. **异步调试的“一等公民”支持**:随着 `asyncio` 成为 Python 异步编程的主流,调试协程和事件循环曾是痛点。debugpy 提供了对异步代码的**完整支持,包括表达式求值和在 `asyncio` 上下文中的调试控制台交互**。这让调试复杂的异步应用变得可行且直观。 1. **一致的调试体验**:debugpy 现在也是 Jupyter 笔记本的默认调试后端。这种统一性减少了认知切换成本。 这个改变,在我看来,是 JetBrains 一次非常务实且具有远见的战略智慧。 - **承认生态的力量**:通过拥抱 debugpy,PyCharm 实际上是承认了在调试器领域,一个由社区和竞争对手(微软)共同塑造的开放标准(DAP)已经胜出。与其维护一个日渐孤立的专有调试器,不如将精力投入到对标准协议的深度集成和优化上。 - **降低用户的切换成本**:debugpy 也是 VS Code 等编辑器的默认调试器。这意味着开发者可以在 PyCharm 和其他工具之间更平滑地切换,因为他们面对的调试交互和核心行为是相似的。这对那些需要在多个 IDE 周旋的团队来说,尤其有价值。 当然,这次转变也可能存在过渡期。对于深度依赖旧调试器特定行为的极少数老项目,可能需要一些适配。但从长远看,debugpy 作为默认调试器,将使 PyCharm 的调试体验更现代、更快速、更统一。

优秀的个人博客,低调大师

Python 15 个实用的网络编程脚本,提升效率2倍不止

![](https://developer.qcloudimg.com/http-save/yehe-11081884/46d54d0bd585a61be2d334caf609a874.jpg) 15 个实用的网络编程脚本覆盖 HTTP、TCP、UDP、FTP、异步、邮件、DNS 等常见场景,代码改改路径和参数基本能直接跑。 --- ## **1. HTTP GET 请求** 用 `requests` 发 GET 请求,拿到网页 HTML。最简单的网络操作,检查网站可访问性也可以用这个。 ``` importrequests url = 'https://www.example.com' response = requests.get(url) print(response.text) # 输出网页HTML源码 ``` --- ## **2. POST 数据到服务器** 向接口提交 JSON 数据,模拟用户登录、API 调用等场景。 ``` importrequests data = {'username': 'test', 'password': '123456'} response = requests.post('https://httpbin.org/post', json=data) print(response.json()) # 解析并打印服务器返回的JSON响应 ``` --- ## **3. TCP 客户端(Socket 基础)** 用 `socket` 模块建立 TCP 连接,适合和非 HTTP 服务通信,比如自定义协议的数据库或游戏服务器。 ``` importsocket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('www.google.com', 80)) client.sendall(b'GET / HTTP/1.1\r\nHost: google.com\r\n\r\n') response = client.recv(4096) print(response.decode('utf-8')) client.close() ``` --- ## **4. 端口扫描** 尝试连接指定端口,检测是否开放。只在自己有权限的机器上用,扫别人的服务器请先授权。 ``` importsocket defport_scanner(host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) try: sock.connect((host, port)) print(f'端口 {port} 开放') returnTrue except (socket.timeout, ConnectionRefusedError): returnFalse finally: sock.close() # 扫描本地80和443端口 port_scanner('localhost', 80) port_scanner('localhost', 443) ``` --- ## **5. UDP 广播** 在局域网内广播消息,所有监听该端口的设备都能收到。适合局域网设备发现、服务通告。 ``` importsocket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) message = b'Device Discovery Hello!' sock.sendto(message, ('', 37020)) sock.close() ``` --- ## **6. FTP 文件下载** 用 `ftplib` 连接 FTP 服务器下载文件,适合自动化备份或从公共 FTP 拉取资源。 ``` fromftplibimportFTP defdownload_file(ftp, remote_path, local_path): withopen(local_path, 'wb') asf: ftp.retrbinary('RETR '+remote_path, f.write) ftp = FTP('ftp.example.com') ftp.login(user='your_username', passwd='your_password') download_file(ftp, '/pub/example.txt', './local_example.txt') ftp.quit() ``` --- ## **7. 简易 HTTP 服务器** 用标准库 `http.server` 起一个本地服务,本地开发测试、快速共享文件用得上。 ``` fromhttp.serverimportHTTPServer, BaseHTTPRequestHandler classSimpleHandler(BaseHTTPRequestHandler): defdo_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(b'Hello from Python Web Server!') server = HTTPServer(('localhost', 8080), SimpleHandler) print('服务器运行在 http://localhost:8080') server.serve_forever() ``` --- ## **8. 多线程并发请求** 用 `ThreadPoolExecutor` 同时发多个 HTTP 请求,批量抓取或并行调 API 时能明显加速。 ``` importrequests fromconcurrent.futuresimportThreadPoolExecutor, as_completed urls = [ 'https://httpbin.org/get', 'https://api.github.com', 'https://www.example.com' ] deffetch_url(url): resp = requests.get(url) returnurl, resp.status_code withThreadPoolExecutor(max_workers=3) asexecutor: future_to_url = {executor.submit(fetch_url, url): urlforurlinurls} forfutureinas_completed(future_to_url): url, status = future.result() print(f'{url} -> 状态码: {status}') ``` --- ## **9. 多客户端聊天室(服务器端)** 每来一个连接就开一个线程处理,适合学习多线程网络编程,或者搭个局域网内的简单即时通讯原型。 ``` importsocket importthreading defhandle_client(client_socket, address): print(f'新连接来自: {address}') whileTrue: try: message = client_socket.recv(1024).decode('utf-8') ifnotmessage: break print(f'收到来自 {address} 的消息: {message}') # 这里可以添加广播给其他客户端的逻辑 client_socket.send(f'服务器已收到: {message}'.encode('utf-8')) exceptConnectionResetError: break client_socket.close() print(f'连接关闭: {address}') server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('0.0.0.0', 9999)) server.listen(5) print('聊天室服务器启动,监听端口 9999...') whileTrue: client_sock, addr = server.accept() client_thread = threading.Thread(target=handle_client, args=(client_sock, addr)) client_thread.start() ``` --- ## **10. 网络爬虫(提取链接)** 用 `requests` 抓页面,`BeautifulSoup` 解析 HTML,提取所有超链接。用之前记得看目标站的 `robots.txt`。 ``` importrequests frombs4importBeautifulSoup url = 'https://www.example.com' try: response = requests.get(url, timeout=5) soup = BeautifulSoup(response.text, 'html.parser') links = [a.get('href') forainsoup.find_all('a', href=True)] forlinkinlinks[:10]: # 打印前10个链接 print(link) exceptrequests.RequestExceptionase: print(f'请求失败: {e}') ``` --- ## **11. 自定义请求头** 加上 `User-Agent`、`Cookie` 等请求头,绕过简单的反爬检测,模拟浏览器访问。 ``` importrequests headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept-Language': 'zh-CN,zh;q=0.9', } cookies = {'session_id': 'your_session_id_here'} response = requests.get('https://httpbin.org/headers', headers=headers, cookies=cookies) print(response.json()) ``` --- ## **12. 异步 HTTP 客户端(aiohttp)** `aiohttp` + `asyncio` 做异步请求,I/O 密集的场景比多线程更省资源,适合高并发爬虫或微服务间通信。 ``` importaiohttp importasyncio asyncdeffetch(session, url): asyncwithsession.get(url) asresponse: returnawaitresponse.text() asyncdefmain(): asyncwithaiohttp.ClientSession() assession: html = awaitfetch(session, 'https://www.example.com') print(html[:500]) # 打印前500个字符 asyncio.run(main()) ``` --- ## **13. XML-RPC 调用** 用标准库 `xmlrpc.client` 调用 XML-RPC 接口,WordPress、MediaWiki 等系统都支持这个协议。 ``` fromxmlrpc.clientimportServerProxy # 连接一个公共的测试服务 server = ServerProxy('https://httpbin.org/xml') # 调用远程方法(示例,实际方法名需查看API文档) try: # 假设存在一个 `example.method` 的方法 # result = server.example.method('arg1') # print(result) print('XML-RPC客户端已就绪,请根据实际API文档调用方法。') exceptExceptionase: print(f'调用失败: {e}') ``` --- ## **14. SMTP 发邮件** 用 `smtplib` 连 SMTP 服务器发邮件,常见于系统告警、注册验证码、自动报表。注意用应用专用密码而不是账户密码。 ``` importsmtplib fromemail.mime.textimportMIMEText fromemail.headerimportHeader sender = 'your_email@gmail.com' receiver = 'receiver_email@example.com' password = 'your_app_password' # 注意:使用应用专用密码 message = MIMEText('这是一封来自Python的测试邮件。', 'plain', 'utf-8') message['From'] = Header(sender, 'utf-8') message['To'] = Header(receiver, 'utf-8') message['Subject'] = Header('Python SMTP 测试邮件', 'utf-8') try: smtp_obj = smtplib.SMTP_SSL('smtp.gmail.com', 465) smtp_obj.login(sender, password) smtp_obj.sendmail(sender, [receiver], message.as_string()) print('邮件发送成功') smtp_obj.quit() exceptsmtplib.SMTPExceptionase: print(f'邮件发送失败: {e}') ``` --- ## **15. DNS 查询** 用 `socket.getaddrinfo` 把域名解析成 IP,写网络诊断工具或需要获取服务 IP 时用得上。 ``` importsocket defresolve_dns(hostname): try: # 获取地址信息,返回 (family, type, proto, canonname, sockaddr) addr_info = socket.getaddrinfo(hostname, None) ips = {info[4][0] forinfoinaddr_info} # 提取IP地址,去重 returnlist(ips) exceptsocket.gaierrorase: returnf'DNS解析失败: {e}' hostname = 'www.google.com' ip_addresses = resolve_dns(hostname) print(f'{hostname} 解析到的IP地址: {ip_addresses}') ``` **“无他,惟手熟尔”!**有需要的用起来! **如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐**❤!

优秀的个人博客,低调大师

Python 30个实用技巧,早用早知道,提升效率

![](https://developer.qcloudimg.com/http-save/yehe-11081884/46d54d0bd585a61be2d334caf609a874.jpg) Python 写多了会慢慢发现,语法本身藏着不少好用的东西,但不是每个人都会去翻文档把它们挖出来。下面整理了 30 个从基础到进阶的技巧,每条附带可直接跑的代码,按需取用。 --- ### **1. 海象运算符(Python 3.8+)** Python 3.8 引入的 `:=` 可以在表达式里直接赋值,省掉一次单独的赋值语句: ``` # 传统写法 lines = [] whileTrue: line = input() ifnotline: break lines.append(line) # 使用海象运算符 lines = [] while (line := input()): lines.append(line) ``` --- ### **2. 类型提示** 类型提示不影响运行,但 IDE 的补全和 mypy 的静态检查都依赖它。写库或者多人协作时特别省事: ``` fromtypingimportOptional, List, Tuple defprocess_data( data: List[int], threshold: Optional[int] = None ) ->Tuple[List[int], int]: """处理数据并返回结果和计数""" ifthresholdisNone: threshold = 0 filtered = [xforxindataifx>threshold] returnfiltered, len(filtered) ``` --- ### **3. pathlib 处理文件路径** 用字符串拼路径是老写法,`pathlib` 更直观,也跨平台: ``` frompathlibimportPath data_dir = Path("data") data_dir.mkdir(exist_ok=True) file_path = data_dir/"output.txt" file_path.write_text("Hello, Python!") content = file_path.read_text() print(content) ``` --- ### **4. 字典 get 方法设置默认值** 访问字典里不存在的键会直接抛 `KeyError`,用 `get` 可以给个默认值兜底: ``` user_preferences = {"theme": "dark", "language": "zh"} theme = user_preferences.get("theme", "light") font_size = user_preferences.get("font_size", 14) # 返回默认值 14 ``` --- ### **5. collections.defaultdict** 需要给字典里每个新键自动初始化一个默认值时,`defaultdict` 比手动判断 `if key not in d` 简洁很多: ``` fromcollectionsimportdefaultdict text = "apple banana apple orange banana apple" word_count = defaultdict(int) forwordintext.split(): word_count[word] += 1 print(dict(word_count)) # {'apple': 3, 'banana': 2, 'orange': 1} ``` --- ### **6. enumerate 获取索引和值** 遍历时需要索引,不用 `range(len(...))`,直接用 `enumerate`: ``` fruits = ["apple", "banana", "orange", "grape"] fori, fruitinenumerate(fruits, start=1): # 从 1 开始计数 print(f"{i}. {fruit}") ``` --- ### **7. zip 并行遍历多个序列** 多个列表要一起遍历,用 `zip` 比手动管索引清楚: ``` names = ["Alice", "Bob", "Charlie"] scores = [85, 92, 78] subjects = ["Math", "Science", "English"] forname, score, subjectinzip(names, scores, subjects): print(f"{name} got {score} in {subject}") # 顺手转成字典 result = dict(zip(names, scores)) print(result) # {'Alice': 85, 'Bob': 92, 'Charlie': 78} ``` --- ### **8. 嵌套列表推导式** 列表推导式可以嵌套,生成二维结构时比双层 for 循环紧凑: ``` multiplication_table = [[i*jforjinrange(1, 6)] foriinrange(1, 6)] forrowinmultiplication_table: print(row) # [1, 2, 3, 4, 5] # [2, 4, 6, 8, 10] # ... ``` --- ### **9. any() 和 all()** 判断序列里是否有满足条件的元素,或者全部满足: ``` numbers = [2, 4, 6, 8, 10] all_even = all(n%2 == 0forninnumbers) print(f"All even: {all_even}") # True has_large = any(n>5forninnumbers) print(f"Has number > 5: {has_large}") # True ``` --- ### **10. sorted 多条件排序** `sorted` 的 `key` 参数接收 lambda,可以同时按多个字段排序: ``` students = [ {"name": "Alice", "score": 85, "age": 20}, {"name": "Bob", "score": 92, "age": 19}, {"name": "Charlie", "score": 85, "age": 21}, {"name": "David", "score": 78, "age": 20}, ] # 分数降序,年龄升序 sorted_students = sorted( students, key=lambdax: (-x["score"], x["age"]) ) forstudentinsorted_students: print(f"{student['name']}: score={student['score']}, age={student['age']}") ``` --- ### **11. f-string 格式化** f-string 的格式化能力比很多人用到的强得多: ``` name = "Python" version = 3.11 price = 0.0 print(f"Language: {name:>10}") # 右对齐,宽度 10 print(f"Version: {version:.2f}") # 保留 2 位小数 print(f"Price: ${price:,.2f}") # 千位分隔符 print(f"Hex: {255:#06x}") # 十六进制,宽度 6,前导 0 print(f"Binary: {42:08b}") # 二进制,宽度 8,前导 0 ``` --- ### **12. itertools 处理迭代器** 标准库里的 `itertools` 提供了不少实用的迭代工具,排列组合、无限计数都有: ``` importitertools counter = itertools.count(start=10, step=2) print(next(counter)) # 10 print(next(counter)) # 12 print(next(counter)) # 14 letters = ['A', 'B', 'C'] combinations = list(itertools.combinations(letters, 2)) print(combinations) # [('A', 'B'), ('A', 'C'), ('B', 'C')] permutations = list(itertools.permutations(letters, 2)) print(permutations) # [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')] ``` --- ### **13. contextlib 创建上下文管理器** 用 `@contextmanager` 装饰器可以把普通函数变成上下文管理器,不需要写 `__enter__/__exit__`: ``` fromcontextlibimportcontextmanager importtime @contextmanager deftimer(label: str): start = time.time() try: yield finally: end = time.time() print(f"{label}: {end - start:.4f} seconds") withtimer("Calculation"): result = sum(i**2foriinrange(1000000)) print(f"Result: {result}") ``` --- ### **14. dataclasses 简化类定义** 主要用来存数据的类,用 `@dataclass` 比手写 `__init__/__repr__/__eq__` 省很多: ``` fromdataclassesimportdataclass, field fromtypingimportList fromdatetimeimportdatetime @dataclass(order=True) classProduct: name: str price: float category: str = "General" tags: List[str] = field(default_factory=list) created_at: datetime = field(default_factory=datetime.now) defdisplay_price(self) ->str: returnf"${self.price:.2f}" product1 = Product("Laptop", 999.99, "Electronics", ["tech", "portable"]) product2 = Product("Book", 29.99, "Education") print(product1) print(f"Formatted price: {product1.display_price()}") print(f"product1 > product2: {product1 > product2}") ``` --- ### **15. partial 固定函数参数** `functools.partial` 可以预先固定函数的某些参数,生成一个新的可调用对象: ``` fromfunctoolsimportpartial defpower(base: float, exponent: float) ->float: returnbase**exponent square = partial(power, exponent=2) cube = partial(power, exponent=3) print(f"Square of 5: {square(5)}") # 25.0 print(f"Cube of 3: {cube(3)}") # 27.0 ``` --- ### **16. lru_cache 缓存函数结果** 对于重复计算成本高的函数,加一个 `@lru_cache` 就能自动缓存结果: ``` fromfunctoolsimportlru_cache importtime @lru_cache(maxsize=128) deffibonacci(n: int) ->int: ifnfloat: return (self.x**2+self.y**2+self.z**2) **0.5 p1 = Point3D(1.0, 2.0, 3.0) p2 = Point3D(4.0, 5.0, 6.0) print(f"Point 1: {p1}") print(f"Distance from origin: {p1.distance_from_origin():.2f}") print(f"Points are equal: {p1 == p2}") ``` --- ### **18. ChainMap 合并多个字典** 有多层配置(默认值、用户配置、环境变量)时,`ChainMap` 比手动合并字典更清晰,优先级也更好控制: ``` fromcollectionsimportChainMap default_config = {"theme": "light", "language": "en", "debug": False} user_config = {"theme": "dark", "font_size": 14} env_config = {"debug": True} # 优先级:env_config > user_config > default_config config = ChainMap(env_config, user_config, default_config) print(f"Theme: {config['theme']}") # 来自 user_config print(f"Language: {config['language']}") # 来自 default_config print(f"Debug: {config['debug']}") # 来自 env_config ``` --- ### **19. 海象运算符配合正则** `:=` 在 for 循环里结合 `re.match` 特别好用,省掉了先 match 再判断 `if match` 的步骤: ``` importre lines = [ "Error: File not found", "Warning: Low disk space", "Info: Process started", "Error: Permission denied", ] errors = [] forlineinlines: ifmatch := re.match(r"Error: (.+)", line): errors.append(match.group(1)) print(f"Errors found: {errors}") # 列表推导式里也能用 data = [1, 2, 3, 4, 5] processed = [n_squaredforxindataif (n_squared := x**2) >10] print(f"Squares > 10: {processed}") ``` --- ### **20. 解包操作符** Python 3.5+ 的扩展解包,合并列表、字典都很方便: ``` first, *middle, last = [1, 2, 3, 4, 5] print(f"First: {first}, Middle: {middle}, Last: {last}") # 合并字典(Python 3.9+) dict1 = {"a": 1, "b": 2} dict2 = {"b": 3, "c": 4} merged = dict1|dict2 print(f"Merged dict: {merged}") # 函数参数解包 defconnect(host, port, timeout=30): print(f"Connecting to {host}:{port} (timeout: {timeout})") server_config = {"host": "example.com", "port": 8080, "timeout": 60} connect(**server_config) # 合并列表 list1 = [1, 2, 3] list2 = [4, 5, 6] combined = [*list1, *list2] print(f"Combined list: {combined}") ``` --- ### **21.** **`__slots__` 减少内存占用** 需要创建大量实例的类,加 `__slots__` 可以显著减少每个实例的内存开销: ``` classPlayer: __slots__ = ('name', 'score', 'level') def__init__(self, name: str, score: int = 0, level: int = 1): self.name = name self.score = score self.level = level deflevel_up(self): self.level += 1 self.score += 100 players = [Player(f"Player{i}", i*100, i//10+1) foriinrange(1000)] importsys player_instance = Player("Test") print(f"Memory size of Player instance: {sys.getsizeof(player_instance)} bytes") ``` --- ### **22. property 装饰器** 用 `@property` 可以把方法包装成属性访问,在赋值时加验证逻辑也很自然: ``` classCircle: def__init__(self, radius: float): self._radius = radius @property defradius(self) ->float: returnself._radius @radius.setter defradius(self, value: float): ifvaluefloat: return2*self._radius @diameter.setter defdiameter(self, value: float): self._radius = value/2 @property defarea(self) ->float: return3.14159*self._radius**2 circle = Circle(5.0) print(f"Radius: {circle.radius}") print(f"Area: {circle.area:.2f}") circle.diameter = 20.0 print(f"New radius after setting diameter: {circle.radius}") ``` --- ### **23. classmethod 和 staticmethod** `@staticmethod` 不依赖实例或类,纯粹是挂在类名下的工具函数;`@classmethod` 拿到的是类本身,常用作替代构造函数: ``` classTemperatureConverter: @staticmethod defcelsius_to_fahrenheit(celsius: float) ->float: returncelsius*9/5+32 @staticmethod deffahrenheit_to_celsius(fahrenheit: float) ->float: return (fahrenheit-32) *5/9 @classmethod deffrom_string(cls, temp_str: str): value, unit = temp_str.split() value = float(value) ifunit.upper() == 'C': returncls(value, 'C') elifunit.upper() == 'F': celsius = cls.fahrenheit_to_celsius(value) returncls(celsius, 'C') else: raiseValueError(f"Unknown unit: {unit}") def__init__(self, value: float, unit: str = 'C'): self.celsius = valueifunit.upper() == 'C'elseself.fahrenheit_to_celsius(value) @property deffahrenheit(self) ->float: returnself.celsius_to_fahrenheit(self.celsius) def__str__(self): returnf"{self.celsius:.1f}°C ({self.fahrenheit:.1f}°F)" print(f"37°C in Fahrenheit: {TemperatureConverter.celsius_to_fahrenheit(37):.1f}") temp1 = TemperatureConverter(25, 'C') print(f"Temperature 1: {temp1}") temp2 = TemperatureConverter.from_string("98.6 F") print(f"Temperature 2: {temp2}") ``` --- ### **24. 抽象基类(abc)** 用 `ABC` 定义接口,强制子类实现指定方法,防止漏掉: ``` fromabcimportABC, abstractmethod fromtypingimportList classDataProcessor(ABC): @abstractmethod defload_data(self, source: str) ->List[dict]: pass @abstractmethod defprocess(self, data: List[dict]) ->List[dict]: pass @abstractmethod defsave_result(self, data: List[dict], destination: str) ->bool: pass defrun_pipeline(self, source: str, destination: str) ->bool: try: data = self.load_data(source) processed_data = self.process(data) returnself.save_result(processed_data, destination) exceptExceptionase: print(f"Pipeline failed: {e}") returnFalse classCSVProcessor(DataProcessor): defload_data(self, source: str) ->List[dict]: print(f"Loading CSV data from {source}") return [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}] defprocess(self, data: List[dict]) ->List[dict]: importdatetime foritemindata: item["processed_at"] = datetime.datetime.now().isoformat() returndata defsave_result(self, data: List[dict], destination: str) ->bool: print(f"Saving processed data to {destination}") returnTrue processor = CSVProcessor() success = processor.run_pipeline("input.csv", "output.csv") print(f"Pipeline completed: {success}") ``` --- ### **25. async/await 异步编程** I/O 密集型任务(比如同时请求多个接口)用异步可以大幅提升吞吐: ``` importasyncio importaiohttp importtime fromtypingimportList asyncdeffetch_url(session: aiohttp.ClientSession, url: str) ->str: asyncwithsession.get(url) asresponse: returnawaitresponse.text() asyncdeffetch_multiple_urls(urls: List[str]): asyncwithaiohttp.ClientSession() assession: tasks = [fetch_url(session, url) forurlinurls] results = awaitasyncio.gather(*tasks, return_exceptions=True) returnresults asyncdefmain(): urls = [ "https://httpbin.org/delay/1", "https://httpbin.org/delay/2", "https://httpbin.org/delay/1", ] start_time = time.time() results = awaitfetch_multiple_urls(urls) print(f"Fetched {len(urls)} URLs in {time.time() - start_time:.2f} seconds") fori, resultinenumerate(results): ifisinstance(result, Exception): print(f"URL {i+1} failed: {result}") else: print(f"URL {i+1} response length: {len(result)}") # asyncio.run(main()) print("Note: Async code requires asyncio.run() to execute") ``` --- ### **26. 描述符控制属性访问** 描述符可以把验证逻辑抽出来复用,不用在每个属性的 setter 里重复写: ``` classValidatedAttribute: def__init__(self, min_value=None, max_value=None, allowed_values=None): self.min_value = min_value self.max_value = max_value self.allowed_values = allowed_values self.name = None def__set_name__(self, owner, name): self.name = name def__get__(self, obj, objtype=None): ifobjisNone: returnself returnobj.__dict__.get(self.name) def__set__(self, obj, value): self._validate(value) obj.__dict__[self.name] = value def_validate(self, value): ifself.min_valueisnotNoneandvalue= {self.min_value}") ifself.max_valueisnotNoneandvalue>self.max_value: raiseValueError(f"{self.name} must be float: returnself.price*self.quantity try: laptop = Product("Laptop", 999.99, 10, "Electronics") print(f"Total value: ${laptop.total_value:.2f}") laptop.price = -100 # 触发 ValueError exceptValueErrorase: print(f"Validation error: {e}") try: invalid_product = Product("Test", 50, 2000, "Unknown") exceptValueErrorase: print(f"Validation error: {e}") ``` --- ### **27. 元类实现单例** 元类是 Python 里比较深的特性,最常见的实际用途之一是实现单例: ``` classSingletonMeta(type): _instances = {} def__call__(cls, *args, **kwargs): ifclsnotincls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) returncls._instances[cls] classDatabaseConnection(metaclass=SingletonMeta): def__init__(self, connection_string: str): self.connection_string = connection_string self._connected = False print(f"Initializing connection to {connection_string}") defconnect(self): ifnotself._connected: print("Establishing connection...") self._connected = True returnself._connected defexecute_query(self, query: str): ifnotself._connected: raiseRuntimeError("Not connected to database") returnf"Result of: {query}" db1 = DatabaseConnection("mysql://localhost:3306/mydb") db1.connect() db2 = DatabaseConnection("mysql://localhost:3306/mydb") # 不会重新初始化 print(f"db1 is db2: {db1 is db2}") # True print(db1.execute_query("SELECT * FROM users")) print(db2.execute_query("SELECT * FROM products")) ``` --- ### **28. 装饰器:retry + timer** 装饰器可以叠加使用,下面是两个实用的例子——计时和自动重试: ``` importtime importfunctools fromtypingimportCallable, Any defretry(max_attempts: int = 3, delay: float = 1.0): defdecorator(func: Callable) ->Callable: @functools.wraps(func) defwrapper(*args, **kwargs) ->Any: last_exception = None forattemptinrange(1, max_attempts+1): try: print(f"Attempt {attempt}/{max_attempts}...") returnfunc(*args, **kwargs) exceptExceptionase: last_exception = e ifattemptCallable: @functools.wraps(func) defwrapper(*args, **kwargs) ->Any: start_time = time.time() result = func(*args, **kwargs) print(f"{func.__name__} took {time.time() - start_time:.4f} seconds") returnresult returnwrapper @timer @retry(max_attempts=2, delay=0.5) defunstable_operation(should_fail: bool = True): ifshould_fail: raiseRuntimeError("Operation failed!") return"Success" try: result = unstable_operation(should_fail=True) exceptExceptionase: print(f"Operation failed with: {e}") ``` --- ### **29. warnings 模块** 标记废弃 API 或者给用户提示非致命问题,用 `warnings` 比直接 `print` 更规范——调用方可以选择过滤或捕获: ``` importwarnings importdatetime defprocess_data(data, use_old_method=False): ifuse_old_method: warnings.warn( "Old method is deprecated and will be removed in v2.0. " "Use the default method instead.", DeprecationWarning, stacklevel=2 ) returnf"Old result: {len(data)}" returnf"New result: {sum(data)}" defcheck_expiry(expiry_date): today = datetime.date.today() ifexpiry_date

优秀的个人博客,低调大师

Python 命令行参数解析的3个方法,提升脚本效率

![](https://developer.qcloudimg.com/http-save/yehe-11081884/46d54d0bd585a61be2d334caf609a874.jpg) 在**Python**开发中,能够接收和处理命令行参数可以让Python脚本更加灵活和强大。本文将介绍三种实用的**Python**命令行参数解析方法及代码示例。 ## **方法一:使用sys.argv** `**sys.argv`**是**Python**内置的最简单的参数解析方式,适合快速开发小型脚本。 ``` import sys def main(): if len(sys.argv) [--verbose]") sys.exit(1) filename = sys.argv[1] verbose = "--verbose" in sys.argv print(f"正在处理文件: {filename}") if verbose: print("详细模式已启用") if __name__ == "__main__": main() ``` **运行示例:** ``` python script.py python-filename.py --verbose ``` ![](https://developer.qcloudimg.com/http-save/yehe-11081884/6ba0af40930dce02ccfff5abbb338e0b.png) ## **方法二:使用argparse** `**argparse`**是**Python**标准库中的参数解析模块,功能全面且灵活。 ``` import argparse def create_parser(): parser = argparse.ArgumentParser(description="文件处理工具") parser.add_argument("file", help="要处理的文件") parser.add_argument("-v", "--verbose", action="store_true", help="启用详细输出") parser.add_argument("-o", "--output", help="输出文件名") parser.add_argument("--size", type=int, choices=[1, 2, 4], default=1, help="处理块大小 (1, 2 或 4)") return parser def main(): parser = create_parser() args = parser.parse_args() print(f"处理文件: {args.file}") if args.verbose: print("详细模式已启用") if args.output: print(f"结果将保存到: {args.output}") print(f"使用块大小: {args.size}") if __name__ == "__main__": main() ``` **运行示例:** ``` python script.py input.txt -v -o result.txt --size 2 ``` ![](https://developer.qcloudimg.com/http-save/yehe-11081884/6a7c0a4040fa2c2f0c483372f3898460.png) ## **方法三:使用click** `**click`**是一个第三方库,提供了更加简洁和直观的API。 ``` import click @click.command() @click.argument("file", type=click.Path(exists=True)) @click.option("--verbose", is_flag=True, help="启用详细输出") @click.option("--output", "-o", help="输出文件名") @click.option("--size", type=click.IntRange(1, 4), default=1, help="处理块大小 (1-4)") def process_file(file, verbose, output, size): """一个简单的文件处理工具""" click.echo(f"处理文件: {file}") if verbose: click.echo("详细模式已启用") if output: click.echo(f"结果将保存到: {output}") click.echo(f"使用块大小: {size}") if __name__ == "__main__": process_file() ``` **运行示例:** ``` python script.py input.txt --verbose -o result.txt --size 2 ``` ![](https://developer.qcloudimg.com/http-save/yehe-11081884/87a9ab7fcc446fb334b566c0bedd3b8e.png) ## **总结对比** |方法|适用场景|优点|缺点| | --- | --- | --- | --- | |sys.argv|简单脚本,快速原型开发|无需额外依赖,简单直接|功能有限,需手动处理| |argparse|标准命令行工具,中等复杂度|功能全面,标准库支持|代码量较多,API略复杂| |click|复杂CLI应用,追求代码优雅|API简洁,功能强大,文档完善|需要安装,学习曲线略高| 根据你的项目需求选择合适的工具:简单脚本用`**sys.argv`**,标准工具用`**argparse`**,复杂应用则推荐`**click`**。掌握这三种方法能够轻松应对各种**Python**命令行参数解析需求。 **“无他,惟手熟尔”!**有需要的用起来。 **如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐**❤!

优秀的个人博客,低调大师

【Gradle With Me Pro】插件正式支持 JetBrains 官方授权,版本管理效率狂飙!

大家好,专注解决 Gradle 项目版本管理痛点的「Gradle With Me Pro」插件,已正式上线 JetBrains 官方插件市场并开放官方授权购买! 从此无需复杂配置,一键解锁专业级版本管理能力,让版本升级、依赖查询、徽章生成更高效、更稳定! 🔥 四大核心功能,彻底解放双手 版本一键升降回退(Gradle 专属) 快照版、Release 版全覆盖!输入目标版本,一键提交即可完成全局版本同步,自动展示修改细节,告别手动修改配置文件的繁琐与出错风险,节省 80% 版本调整时间!(支持标准版本格式,特殊场景可随时反馈适配) 版本可视化展示(Gradle 专属) 项目视图直接显示当前版本号,无需打开配置文件即可快速确认版本状态!还支持自定义展示规则,贴合你的开发习惯~ 依赖版本精准搜索(Maven/Gradle 通用) ✅ 中央仓库 + Nexus 仓库(远程 / 私服)双支持,低版本 Nexus 兼容无压力 ✅ 便捷查询:粘贴 pom/Gradle 配置或输入关键字即可秒查最新版本 ✅ 实用工具:一键复制依赖坐标、一键跳转文件目录、加载版本更新时间、直达版本详情页,依赖管理一步到位! 版本徽章快速生成(Maven/Gradle 通用) 依托 shields.io 能力,支持自定义文本、颜色、跳转链接(内置中央仓库 Release 版本链接)!粘贴依赖配置即可快速填充 groupId+artifactId,一键生成专业徽章,让项目文档更直观~ ✨ 为什么选择官方授权版? ✅ 享受 JetBrains 官方安全支付渠道及发票,授权稳定无风险 ✅ 优先获得功能更新、bug 修复支持,适配最新 IDE 版本 ✅ 遇到问题优先响应,定制化需求优先评估 🛒 即刻解锁高效开发 👉 打开 IntelliJ IDEA、Android Studio 等 JetBrains IDE 👉 进入 Plugins 市场,搜索「Gradle With Me Pro」或 「GPVP」 👉 点击「Buy License」完成官方授权,一键激活功能! 版本管理不用愁,Gradle With Me Pro 全搞定!无论是个人开发还是团队协作,都能帮你简化工作流程、节省宝贵时间,让精力聚焦核心业务开发~ 📞 反馈与支持:插件内提交 issue 或通过插件主页的联系方式联系我们,你的建议将驱动我们持续优化! 感谢所有用户的支持与期待,「Gradle With Me Pro」将与 JetBrains 生态深度协同,为你带来更极致的版本管理体验!🚀

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码