timmy / 使用 typing 進行型別註解
0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
typing 模組允許為 Python 變數、函式參數和回傳值指定型別,有助於提升程式碼可讀性、可維護性,並可搭配靜態分析工具(如 mypy)檢查型別錯誤。
| 1 | from typing import Any, Dict, List, Optional, Tuple, Union |
| 2 | |
| 3 | # 函式使用型別註解 |
| 4 | def process_data( |
| 5 | data: List[Dict[str, Union[int, float]]], |
| 6 | metadata: Optional[Dict[str, Any]] = None |
| 7 | ) -> Tuple[int, float]: |
| 8 | """計算資料的總和與平均值""" |
| 9 | total = sum(item["value"] for item in data) |
| 10 | avg = total / len(data) if data else 0 |
timmy / 使用 re 進行正規表示式匹配
0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
re 模組提供強大的正規表示式功能,可用於文字搜尋、字串處理與資料驗證,適用於日誌分析、表單驗證與文字解析等場景。
| 1 | import re |
| 2 | |
| 3 | # 定義正規表示式模式 |
| 4 | pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" |
| 5 | |
| 6 | # 測試字串 |
| 7 | text = "聯絡我們: support@example.com 或 visit@example.org" |
| 8 | |
| 9 | # 搜尋第一個匹配的電子郵件 |
| 10 | match = re.search(pattern, text) |
timmy / 使用 psutil 監控系統資源
0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
| 1 | import psutil |
| 2 | |
| 3 | # 獲取 CPU 使用率 |
| 4 | cpu_usage = psutil.cpu_percent(interval=1) |
| 5 | print(f"CPU 使用率: {cpu_usage}%") |
| 6 | |
| 7 | # 獲取記憶體資訊 |
| 8 | memory_info = psutil.virtual_memory() |
| 9 | print(f"總記憶體: {memory_info.total / (1024**3):.2f} GB") |
| 10 | print(f"可用記憶體: {memory_info.available / (1024**3):.2f} GB") |
timmy / 使用 subprocess 執行系統指令
0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
subprocess 模組可用於執行系統指令、與外部程式互動,適用於自動化腳本、批次處理與系統管理等應用。
| 1 | import subprocess |
| 2 | |
| 3 | # 執行系統指令並獲取輸出 |
| 4 | result = subprocess.run(["ls", "-l"], capture_output=True, text=True) |
| 5 | |
| 6 | # 顯示執行結果 |
| 7 | print("命令輸出:") |
| 8 | print(result.stdout) |
| 9 | |
| 10 | # 檢查是否執行成功 |
timmy / 使用 gc 模組進行垃圾回收管理
0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
gc 模組提供手動管理 Python 垃圾回收(Garbage Collection)的方法,例如調試記憶體洩漏、強制回收、調整閾值等,適用於長時間執行的應用或記憶體優化。
| 1 | import gc |
| 2 | |
| 3 | class CircularReference: |
| 4 | def __init__(self): |
| 5 | self.ref = self # 建立循環引用 |
| 6 | |
| 7 | # 建立一個有循環引用的物件 |
| 8 | obj = CircularReference() |
| 9 | |
| 10 | # 檢查物件是否被垃圾回收 |
timmy / 使用 pickle 進行物件序列化與反序列化
0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
pickle 模組可將 Python 物件轉換為二進位格式(序列化),並存儲到檔案或傳輸,之後可還原為原始物件(反序列化),適用於暫存數據、跨進程通訊或模型儲存。
| 1 | import pickle |
| 2 | |
| 3 | # 定義要序列化的物件(字典) |
| 4 | data = { |
| 5 | "name": "Timmy", |
| 6 | "age": 30, |
| 7 | "skills": ["Python", "Docker", "JavaScript"] |
| 8 | } |
| 9 | |
| 10 | # 將物件序列化並存入檔案 |
timmy / 使用 shutil 進行檔案與目錄操作
0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
shutil 模組提供高級的檔案與目錄管理功能,包括複製、移動、壓縮與刪除,適用於備份、部署與自動化檔案管理。
| 1 | import shutil |
| 2 | import os |
| 3 | |
| 4 | # 定義來源與目標 |
| 5 | source_file = "example.txt" |
| 6 | destination_dir = "backup/" |
| 7 | destination_file = os.path.join(destination_dir, source_file) |
| 8 | |
| 9 | # 確保目標目錄存在 |
| 10 | os.makedirs(destination_dir, exist_ok=True) |
timmy / 使用 multiprocessing.Pipe 進行進程間通訊
0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
multiprocessing.Pipe 允許 Python 進程之間傳遞資料,適用於需要高效能、雙向通訊的場景,如併發運算或分佈式處理。
| 1 | from multiprocessing import Process, Pipe |
| 2 | |
| 3 | def worker(conn): |
| 4 | conn.send("Hello from child process") # 傳送訊息 |
| 5 | msg = conn.recv() # 接收訊息 |
| 6 | print(f"Child received: {msg}") |
| 7 | conn.close() |
| 8 | |
| 9 | if __name__ == "__main__": |
| 10 | parent_conn, child_conn = Pipe() # 建立 Pipe 雙向通道 |
timmy / 使用 traceback 來捕捉與記錄異常
0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
traceback 模組可用於捕捉、格式化和記錄 Python 例外發生時的詳細資訊,有助於錯誤診斷與日誌記錄。
| 1 | import traceback |
| 2 | |
| 3 | def faulty_function(): |
| 4 | return 1 / 0 # 這將觸發 ZeroDivisionError |
| 5 | |
| 6 | try: |
| 7 | faulty_function() |
| 8 | except Exception as e: |
| 9 | error_message = f"Exception occurred: {str(e)}" |
| 10 | stack_trace = traceback.format_exc() |