CUP(通用實用 Python):用百度工具套件打造可靠的 Python 工作流程
重點摘要
在本教學中,我們深入探討百度推出的 CUP(Common Useful Python)函式庫,這是一套實用的工具套件,能協助建立更穩健的 Python 工作流程。我們先在適合 Colab 的環境中安裝該函式庫,接著逐步介紹其主要子系統,包括日誌記錄、裝飾器、巢狀設定、快取、ID 生成、執行緒池、可中斷執行緒、延遲執行、時間工具、Linux 資源監控、檔案鎖定、網路輔助功能、物件儲存介面、型別對應,以及內建測試斷言。過程中,我們並非隨意呼叫函式,而是觀察每個模組如何應用於實際開發任務,例如監控、自動化、並行處理、設定管理與可靠性檢查。CUP 安裝與日誌記錄程式碼範例
In this tutorial, we explore CUP, Baidu’s Common Useful Python library, as a practical utility toolkit for building stronger Python workflows. We begin by setting up the library in a Colab-friendly environment and then move through its major subsystems step by step, including logging, decorators, nested configuration, caching, ID generation, thread pools, interruptible threads, delayed execution, time utilities, Linux resource monitoring, file locking, networking helpers, object storage interfaces, type maps, and built-in testing assertions. As we progress, we do not just call functions at random; we observe how each module fits into real-world development tasks such as monitoring, automation, concurrency, configuration management, and reliability checks. CUP Setup and Logging Copy CodeCopiedUse a different Browserimport os import sys import time import threading import tempfile import datetime import subprocess def banner(title): line = "=" * 70 print("\n" + line + "\n" + title + "\n" + line) def skip(exc): """Report a gracefully-skipped section without aborting the notebook.""" print(" [skipped — {}: {}]".format(type(exc).__name__, exc)) banner("0. SETUP (install + cup.platforms + cup.version)") subprocess.run( [sys.executable, "-m", "pip", "install", "-q", "cup", "pytz"], check=False, ) import cup ver = getattr(cup, "__version__", None) if ver is None: try: from cup import version as _v ver = getattr(_v, "VERSION", None) or getattr(_v, "__version__", "unknown") except Exception: ver = "unknown" print("CUP version :", ver) print("Python :", sys.version.split()[0]) try: from cup import platforms print("is_linux :", platforms.is_linux()) print("is_mac :", platforms.is_mac()) print("is_windows :", platforms.is_windows()) print("is_py3 :", platforms.is_py3()) except Exception as e: skip(e) banner("1. LOGGING (cup.log)") LOGFILE = os.path.join(tempfile.gettempdir(), "cup_tutorial.log") try: from cup import log log.init_comlog( "cup_tutorial", log.INFO, LOGFILE, log.ROTATION, 10 * 1024 * 1024, True, False, ) log.info("hello from cup.log — written to file AND stdout") log.warning("a warning line") log.info_if(2 > 1, "info_if(True) -> emitted") log.info_if(1 > 2, "info_if(False) -> you will NOT see this") log.setloglevel(log.DEBUG) log.debug("debug visible after setloglevel(DEBUG)") try: with open(LOGFILE) as fh: last = [ln for ln in fh.read().splitlines() if ln.strip()][-1] parsed = log.parse(last) print("parsed last log line ->") for k in ("loglevel", "date", "time", "pid", "srcline", "msg"): if isinstance(parsed, dict) and k in parsed: print(" {:8}: {}".format(k, parsed[k])) except Exception as e: skip(e) except Exception as e: skip(e) We begin by setting up the CUP tutorial environment and installing the required packages directly from Python. We define helper functions that keep the notebook readable and allow failed sections to be skipped safely. We then explore CUP version details, platform checks, and structured logging to understand the library’s foundation. Decorators and Nested Config Copy CodeCopiedUse a different Browserbanner("2. DECORATORS (cup.decorators)") try: from cup import decorators @decorators.Singleton class AppConfig(object): def __init__(self): self.created_at = time.time() a, b = AppConfig(), AppConfig() print("Singleton: a is b ->", a is b, "(same created_at:", a.created_at == b.created_at, ")") @decorators.TraceUsedTime( b_print_stdout=True, enter_msg="event_id=0xABCDE enter", leave_msg="event_id=0xABCDE leave", ) def heavy_compute(): time.sleep(0.2) return sum(range(200000)) print("heavy_compute() =", heavy_compute()) @decorators.needlinux def linux_only(): return "this body is allowed to run on Linux" print("needlinux ->", linux_only()) except Exception as e: skip(e) banner("3. RICH NESTED CONFIG (cup.util.conf)") CONF_PATH = os.path.join(tempfile.gettempdir(), "cup_demo.conf") CONF_TEXT = """\ # ---- global scalars (layer 0) ---- host: abc.com port: 12345 debug: false [monitor] enabled: true interval: 60 regex: sshd [.thresholds] cpu_max: 90 mem_max: 80 [..actions] on_breach: alert [storage] @path: /data/disk1 @path: /data/disk2 @path: /data/disk3 """ try: from cup.util import conf with open(CONF_PATH, "w") as fh: fh.write(CONF_TEXT) cfg = conf.Configure2Dict(CONF_PATH, separator=":").get_dict() print("host :", cfg["host"]) print("port :", cfg["port"]) print("monitor.enabled :", cfg["monitor"]["enabled"]) print("monitor.regex :", cfg["monitor"]["regex"]) print("monitor.thresholds.cpu_max :", cfg["monitor"]["thresholds"]["cpu_max"]) print("monitor.thresholds.actions :", cfg["monitor"]["thresholds"]["actions"]["on_breach"]) print("storage.path (repeated @ -> list):", list(cfg["storage"]["path"])) cfg["port"] = "10085" cfg["monitor"]["thresholds"]["actions"]["on_breach"] = "restart" NEW_PATH = CONF_PATH + ".new" conf.Dict2Configure(cfg, separator=":").write_conf(NEW_PATH) re_read = conf.Configure2Dict(NEW_PATH, separator=":").get_dict() print("round-trip port :", re_read["port"], "(was 12345)") print("round-trip on_breach :", re_read["monitor"]["thresholds"]["actions"]["on_breach"], "(was alert)") except Exception as e: skip(e) We move on to CUP decorators and see how they help us create single-instance classes, track execution time, and protect Linux-only functions. We then work with CUP’s rich configuration system and load a nested configuration file with sections, child sections, and repeated values. We also update the configuration and write it back to disk to confirm that the read-modify-write flow works correctly. Caching, IDs, Thread Pools Copy CodeCopiedUse a different Browserbanner("4. IN-MEMORY KV CACHE (cup.cache)") try: from cup import cache kv = cache.KVCache(name="demo") kv.set({"user:1": "alice", "user:2": "bob"}, expire_sec=2) kv.set({"config:flag": "on"}, expire_sec=None) print("size after sets :", kv.size()) print("get user:1 :", kv.get("user:1")) print("get missing key :", kv.get("nope")) print("sleeping 2.2s to let the 2s-TTL keys expire ...") time.sleep(2.2) print("get user:1 (expired) :", kv.get("user:1")) print("get config:flag (eternal):", kv.get("config:flag")) reclaimed = kv.pop_n_expired(0) print("pop_n_expired reclaimed :", list(reclaimed.keys()) if reclaimed else []) except Exception as e: skip(e) banner("5. UNIQUE ID GENERATION (cup.services.generator)") try: from cup.services import generator gman = generator.CGeneratorMan() print("uniqname :", gman.get_uniqname()) print("next_uniq_num :", gman.get_next_uniq_num()) print("next_uniq_num (again) :", gman.get_next_uniq_num(), "(monotonic)") if hasattr(gman, "get_uuid"): try: print("get_uuid :", gman.get_uuid()) except Exception as e: skip(e) if hasattr(gman, "get_random_str"): try: print("get_random_str(16) :", gman.get_random_str(16)) except Exception as e: skip(e) print("singleton check :", generator.CGeneratorMan() is gman) try: cyc = generator.CycleIDGenerator("127.0.0.1", 8080) i1, i2 = cyc.next_id(), cyc.next_id() print("CycleIDGenerator id #1 :", i1) print("CycleIDGenerator id #2 :", i2, "(incremented)") print("id #1 as hex :", generator.CycleIDGenerator.id2_hexstring(i1)) except Exception as e: skip(e) except Exception as e: skip(e) banner("6. THREAD POOL (cup.services.threadpool)") try: from cup.services import threadpool pool = threadpool.ThreadPool(minthreads=2, maxthreads=4, name="demo-pool") pool.start() results, rlock = [], threading.Lock() def square(n): time.sleep(0.03) with rlock: results.append(n * n) return n * n for i in range(8): pool.add_1job(square, i) callback_log = [] def on_done(ok, result): callback_log.append((ok, result)) pool.add_1job_with_callback(on_done, square, 100) def will_fail(): raise RuntimeError("boom inside worker") pool.add_1job_with_callback(on_done, will_fail) time.sleep(0.5) print("live stats :", pool.get_stats()) pool.stop() print("squares collected :", sorted(results)) print("callback results :", callback_log) except Exception as e: skip(e) We use CUP’s in-memory cache to store key-value pairs with tem
Related
相關文章

大廠HR破防了:年輕人用Agent找工作,AI輔助面試太離譜
這篇消息聚焦「大廠HR破防了:年輕人用Agent找工作,AI輔助面試太離譜」。原始導語提到:HR在面AI,你在被AI面。 從 AI 情報角度來看,這類內容值得關注其背後的技術進展、產品落地、產業競爭與後續市場影響。

系列最強智能體 AI 模型:Claude Sonnet 5 登場,部分性能逼近 Opus 4.8
Anthropic 今天(7 月 1 日)發佈公告,宣佈推出 Claude Sonnet 5,聲稱是其 Sonnet 系列中智能體 AI 表現最強的模型,能夠制定計劃、使用瀏覽器和終端等工具,並自主運行。
Agent 落地,數據庫先變
雷峰網訊 AI 的競爭越靠近落地,越展現出其殘酷的一面。Benchmark 上幾分的得失正變得意義有限,取而代之的,是真金白銀的投入產出比。Agent 如何真正讀懂業務,模型智能如何在業務端釋放出更大的價值,成為了這一階段競爭最核心的命題。而一同被推向舞臺中央的,還有數據庫。過去,它扮演的角色很簡單,本質就是一個長期、安全、可查詢的數據存儲系統。比如用戶在淘寶購物,完成了下單、支付、退款、查物流等一系列操作,最基本的需求就是這些記錄不能丟失、不能出錯、可查詢,以及能支撐高峰期幾億人同時下單的高併發壓力。這就是移動互聯網時代數據庫的核心能力,圍繞著存儲和查詢,衍生出一致性、併發處理和容災備份的需求。但是當 Agent 越發深入地走進生產場景,它們也自然而然地成為了數據庫的新用戶。Agent 需要實時訪問各種結構化和非結構化數據,數據庫也從服務於人寫 SQL 查數據的存儲模塊,變成了 Agent 的記憶系統。這個新的角色,意味著數據庫在存儲之外,還要支撐 RAG(檢索增強生成)和實時數據流驅動的 AI。RAG 場景下,AI 回答問題需要從數據庫召回資料再生成回答,沒有數據庫就等於 AI “失憶”。而實時數據流驅動的 AI,更有賴於毫秒到秒級的用戶行為數據實時讀取。這兩者是今天 Agent 落地最常見的兩種場景。可以說,當我們討論 Agent 是否已經邁過那條名為“可用”的界限時,數據庫的重要程度,並不亞於模型智能水平。那麼 AI 時代,到底需要什麼樣的數據庫?01當數據庫開始服務 Agent據 Gartner 預測,到 2028 年,AI Agent 生態系統將能夠使多個專業化的智能體在不同企業應用間動態協作。屆時,約有三分之一的用戶體驗將從使用原生應用,轉向由 Agent 前端來主導。數據庫是這種轉變的一個鮮明代表。當 Agent 成為數據的使用者,對數據庫的訪問頻率將遠遠高
智源 SoulAgent亮相2026全球數字經濟大會,打造智能聽會新體驗
2026 全球數字經濟大會將於 7 月 2 日至 5 日在北京國家會議中心舉辦。本屆大會由北京市人民政府、中國國家互聯網信息辦公室、中國國家數據局、新華通訊社及聯合國開發計劃署、聯合國工業發展組織等聯合主辦,以“智惠無界、數聯全球”為主題,設置“1+1+N”活動框架——一場開幕式、一場“數字友好城市建設全球對話會”主論壇,以及涵蓋工業智能體發展、未來產業、數字友好社區、科技服務業發展等多場專題論壇。 大會累計參會企業上萬家、參會人數達 15 萬人次、覆蓋 200 餘個國家及國際組織、發佈成果 500 項。今年,大會在新加坡、巴塞羅那、日內瓦、中東等海外分會場及拉薩分會場同步聯動,已成為立足普惠均衡、創新包容、合作共贏的全球數字經濟交流合作標誌性平臺。 議程密集、論壇並行:參會者的“分身”難題 四天會期、多場專題論壇密集並行,僅7月3日當天便有數字中亞國際合作論壇與國際電子競技發展論壇,數智廣告創新與發展論壇同期舉辦,7月4日數字新質發展建設專題論壇、數字經濟“她力量”國際論壇隨即接續。場場雲集院士專家、部委代表與頭部企業高管,含金量極高——參會者不得不在多個精彩議程間做出取捨。往屆不少參會者反饋:想聽的場次太多、時間高度重疊,即便全程在場,海量信息也難以即時消化,會後想系統回顧,又苦於缺乏高效的整理工具。眾多媒體也提及面對分散的會議信息,快速產出報道是一大挑戰。 本屆大會引進北京智源人工智能研究院推出的個人智能體 SoulAgent。該產品早在今年 6 月智源大會上已完成萬人級實戰驗證,恰好回應了大型會議場景中“信息獲取”與“知識沉澱”的雙重需求。 SoulAgent:讓 AI 替你“在場” 智源 SoulAgent 是北京智源研究院推出的首款面向個人的專屬智能體。它不只是一次性的問答工具,更能逐步理解用戶的興趣偏好與思維習慣,沉澱長期記憶與個性化認知畫像,在日常陪伴中持續
開源 AI 代理項目 OpenClaw 正式推出 iOS 與 Android 移動版應用
OpenClaw開源AI智能體項目發佈iOS與Android移動應用,用戶可通過設備配對網關,隨時調用AI代理執行程序編寫、膳食規劃等任務。該項目年初走紅,此次實現全平臺覆蓋,進一步推動高自動化智能體落地。

智能體互聯國標發佈:為什麼統一了接口,依然可能連不通物理世界?
這篇消息聚焦「智能體互聯國標發佈:為什麼統一了接口,依然可能連不通物理世界?」。原始導語提到:拆解“智能體破壁”背後的底層邏輯 從 AI 情報角度來看,這類內容值得關注其背後的技術進展、產品落地、產業競爭與後續市場影響。