Python 自動化腳本實戰

Python 2025-01-01T16:00:00.000Z

Python 自動化腳本實戰

Python 是自動化任務的最佳選擇,擁有豐富的標準函式庫與第三方套件。

檔案處理自動化

import shutil
from pathlib import Path

source = Path('/data/reports')
for file in source.glob('*.csv'):
    dest = Path('/backup') / file.name
    shutil.copy(file, dest)
    print(f'Copied {file.name}')

API 排程任務

import schedule
import time
import requests

def fetch_data():
    response = requests.get('https://api.example.com/data')
    print(f'Fetched {len(response.json())} items')

schedule.every(1).hours.do(fetch_data)

while True:
    schedule.run_pending()
    time.sleep(60)

系統監控

import psutil

cpu_percent = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
print(f'CPU: {cpu_percent}%, Memory: {memory.percent}%')

最佳實踐

  • 使用 logging 取代 print
  • 加入例外處理與重試機制
  • 使用 argparse 處理命令列參數