def foo(*args):
print("Number of arguments:", len(args))
for i, x in enumerate(args):
print(f"Argument {i}: {x}")
foo() # 0
foo("hello") # 1: hello
foo("hello", "world") # 2: hello, world
*args 收集位置參數為元組;**kwargs 收集關鍵字參數為字典。
import glob
# 獲取所有 .py 文件
files = glob.glob('*.py')
# 多模式
import itertools
def multi_glob(*patterns):
return itertools.chain.from_iterable(glob.glob(p) for p in patterns)
for f in multi_glob("*.txt", "*.py"):
print(f)
配合 os.path.realpath 獲取絕對路徑。
import logging, inspect
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(filename)s:%(lineno)d: %(message)s')
def debug_info():
frame = inspect.currentframe().f_back
print(frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name)
logging.info("Application started")
debug_info()
inspect.getouterframes() 可獲取完整調用棧,適合構建自定義日誌上下文。
import uuid
uid = uuid.uuid1() # 基於時間+MAC
print(uid) # 9e177ec0-65b6-11e3-b2d0-e4d53dfcf61b
# 去連字號
print(str(uid).replace('-', ''))
# 隨機 UUID (v4)
print(uuid.uuid4())
注意:`uuid1()` 尾部相似因包含 MAC 地址;高安全場景用 `uuid4()` 或加密雜湊。
import pickle, json
data = ['hello', 42, [1, 'two'], 'apple']
# pickle (Python 專用,支援任意對象)
pickled = pickle.dumps(data)
restored = pickle.loads(pickled)
# json (跨語言,僅基本類型)
json_str = json.dumps(data)
restored2 = json.loads(json_str) # 列表變為 Unicode 字符串
複雜對象用 pickle;API 交互、配置文件用 json。
import zlib
text = "Lorem ipsum " * 100
compressed = zlib.compress(text.encode())
print("Original:", len(text), "Compressed:", len(compressed))
decompressed = zlib.decompress(compressed).decode()
assert decompressed == text
無需臨時文件,內存級壓縮,適合網絡傳輸、緩存大文本。
import atexit, time
start = time.time()
def report():
print(f"Runtime: {time.time() - start:.2f}s")
atexit.register(report)
# 程序正常退出、異常退出、sys.exit() 皆會執行
# 不會執行:os._exit()、SIGKILL、解釋器崩潰
優於在腳本末尾寫代碼:即使拋出未捕獲異常也會執行。
import hmac, hashlib
key = b'secret'
msg = b'message'
print(hmac.new(key, msg, hashlib.sha256).hexdigest())
m = hashlib.sha1()
m.update(b"The quick brown fox jumps over the lazy dog")
print(m.hexdigest())
用於 API 簽名、完整性校驗。
| 特性 | 模組/語法 | 典型場景 |
|---|---|---|
| 可變參數 | *args, **kwargs | 裝飾器、代理函數、CLI 工具 |
| 文件匹配 | glob | 批量處理、構建腳本 |
| 調試檢測 | inspect | 動態日誌、測試框架 |
| 唯一 ID | uuid | 分布式追蹤、臨時文件名 |
| 序列化 | pickle / json | 對象持久化 / API 交互 |
| 壓縮 | zlib | 網絡傳輸、緩存優化 |
| 關閉鉤子 | atexit | 資源清理、指標上報 |