1. 为什么需要Python自动化脚本?
在日常工作和生活中,我们经常会遇到大量重复性的任务:文件整理、数据收集、报表生成、系统监控等。这些任务不仅耗时耗力,而且容易出错。作为一名长期与Python打交道的开发者,我发现用Python编写自动化脚本可以显著提升效率。Python凭借其简洁的语法、丰富的库生态和跨平台特性,成为自动化任务的首选语言。
最近几年,Python在自动化领域的应用越来越广泛。从简单的文件处理到复杂的系统管理,从日常办公到专业开发,Python都能提供高效的解决方案。下面我将分享10个经过实战检验的Python自动化脚本,这些脚本可以直接用于你的日常工作,帮你节省大量时间。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 10个实用Python自动化脚本详解
2.1 文件批量重命名脚本
这个脚本可以批量重命名指定目录下的所有文件,支持按序号、日期或自定义规则命名。
python复制import os
def batch_rename(path, prefix):
for count, filename in enumerate(os.listdir(path)):
old_path = os.path.join(path, filename)
new_name = f"{prefix}_{str(count+1).zfill(3)}{os.path.splitext(filename)[1]}"
new_path = os.path.join(path, new_name)
os.rename(old_path, new_path)
print(f"Renamed: {filename} -> {new_name}")
# 使用示例
batch_rename("/path/to/files", "document")
注意事项:运行前建议先备份文件,避免意外覆盖。zfill(3)表示用0填充到3位数,如001。
2.2 自动整理下载文件夹
这个脚本会根据文件扩展名自动将下载文件夹中的文件分类到不同子目录。
python复制import os
import shutil
def organize_downloads(download_path):
file_types = {
"Images": [".jpg", ".png", ".gif"],
"Documents": [".pdf", ".docx", ".txt"],
"Archives": [".zip", ".rar"],
"Executables": [".exe", ".msi"]
}
for filename in os.listdir(download_path):
if os.path.isfile(os.path.join(download_path, filename)):
file_ext = os.path.splitext(filename)[1].lower()
for folder, extensions in file_types.items():
if file_ext in extensions:
if not os.path.exists(os.path.join(download_path, folder)):
os.makedirs(os.path.join(download_path, folder))
shutil.move(
os.path.join(download_path, filename),
os.path.join(download_path, folder, filename)
)
break
# 使用示例
organize_downloads("C:/Users/Username/Downloads")
2.3 网站内容监控脚本
这个脚本可以定期检查网站内容变化,当检测到更新时发送邮件通知。
python复制import requests
import hashlib
import time
import smtplib
from email.mime.text import MIMEText
def monitor_website(url, email, check_interval=3600):
previous_hash = ""
while True:
response = requests.get(url)
current_hash = hashlib.sha256(response.content).hexdigest()
if previous_hash and current_hash != previous_hash:
send_email(email, f"网站内容已更新: {url}")
previous_hash = current_hash
time.sleep(check_interval)
def send_email(to_email, message):
msg = MIMEText(message)
msg["Subject"] = "网站更新通知"
msg["From"] = "monitor@example.com"
msg["To"] = to_email
with smtplib.SMTP("smtp.example.com", 587) as server:
server.login("username", "password")
server.send_message(msg)
# 使用示例
monitor_website("https://example.com", "your@email.com")
提示:需要配置SMTP服务器信息。对于需要登录的网站,可以使用requests.Session()保持会话。
2.4 自动填写网页表单脚本
使用Selenium自动化浏览器操作,自动填写并提交网页表单。
python复制from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
def auto_fill_form(url, form_data):
driver = webdriver.Chrome()
driver.get(url)
for field_name, value in form_data.items():
element = driver.find_element(By.NAME, field_name)
element.clear()
element.send_keys(value)
time.sleep(0.5)
submit_button = driver.find_element(By.XPATH, "//input[@type='submit']")
submit_button.click()
time.sleep(3)
driver.quit()
# 使用示例
form_data = {
"username": "testuser",
"password": "securepassword",
"email": "test@example.com"
}
auto_fill_form("https://example.com/login", form_data)
2.5 批量图片处理脚本
使用Pillow库批量调整图片大小、格式和质量。
python复制from PIL import Image
import os
def batch_process_images(input_dir, output_dir, size=(800, 600), quality=85):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.lower().endswith((".jpg", ".png", ".jpeg")):
try:
img_path = os.path.join(input_dir, filename)
img = Image.open(img_path)
img = img.resize(size, Image.ANTIALIAS)
output_path = os.path.join(output_dir, f"processed_{filename}")
img.save(output_path, quality=quality)
print(f"Processed: {filename}")
except Exception as e:
print(f"Error processing {filename}: {str(e)}")
# 使用示例
batch_process_images("input_images", "output_images")
2.6 自动备份重要文件脚本
定期将指定目录下的文件压缩备份到另一个位置。
python复制import zipfile
import os
from datetime import datetime
import shutil
def backup_files(source_dir, backup_dir, max_backups=5):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"backup_{timestamp}.zip"
backup_path = os.path.join(backup_dir, backup_name)
with zipfile.ZipFile(backup_path, "w", zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(source_dir):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, start=source_dir)
zipf.write(file_path, arcname)
# 清理旧的备份文件
backups = sorted(
[f for f in os.listdir(backup_dir) if f.startswith("backup_")],
key=lambda x: os.path.getmtime(os.path.join(backup_dir, x))
)
while len(backups) > max_backups:
oldest = backups.pop(0)
os.remove(os.path.join(backup_dir, oldest))
return backup_path
# 使用示例
backup_files("important_documents", "backup_location")
2.7 自动发送日报邮件脚本
从数据库或文件中提取数据,生成日报并自动发送给相关人员。
python复制import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime
def send_daily_report(email_list, db_connection):
# 从数据库获取数据
query = "SELECT * FROM daily_metrics WHERE date = CURRENT_DATE"
df = pd.read_sql(query, db_connection)
# 生成HTML报告
report_date = datetime.now().strftime("%Y-%m-%d")
html_content = f"""
<h1>每日报告 - {report_date}</h1>
{df.to_html()}
<p>报告生成时间: {datetime.now()}</p>
"""
# 配置邮件
msg = MIMEMultipart()
msg["Subject"] = f"每日报告 - {report_date}"
msg["From"] = "reports@company.com"
msg.attach(MIMEText(html_content, "html"))
# 发送邮件
with smtplib.SMTP("smtp.company.com", 587) as server:
server.starttls()
server.login("username", "password")
for email in email_list:
msg["To"] = email
server.send_message(msg)
print(f"报告已发送至: {email}")
# 使用示例
recipients = ["manager@company.com", "team@company.com"]
send_daily_report(recipients, "db_connection_string")
2.8 系统资源监控脚本
监控CPU、内存和磁盘使用情况,超过阈值时发出警告。
python复制import psutil
import time
import logging
def monitor_system_resources(cpu_threshold=80, mem_threshold=80, disk_threshold=90, check_interval=60):
logging.basicConfig(
filename="system_monitor.log",
level=logging.WARNING,
format="%(asctime)s - %(levelname)s - %(message)s"
)
while True:
cpu_percent = psutil.cpu_percent(interval=1)
mem_percent = psutil.virtual_memory().percent
disk_percent = psutil.disk_usage("/").percent
if cpu_percent > cpu_threshold:
logging.warning(f"CPU使用率过高: {cpu_percent}%")
if mem_percent > mem_threshold:
logging.warning(f"内存使用率过高: {mem_percent}%")
if disk_percent > disk_threshold:
logging.warning(f"磁盘空间不足: {disk_percent}%")
time.sleep(check_interval)
# 使用示例
monitor_system_resources()
2.9 自动测试脚本执行器
自动运行测试套件并生成测试报告。
python复制import unittest
import time
import os
from html_test_runner import HTMLTestRunner
def run_tests(test_dir="tests", report_dir="reports"):
# 发现所有测试用例
test_suite = unittest.defaultTestLoader.discover(test_dir)
# 创建报告目录
if not os.path.exists(report_dir):
os.makedirs(report_dir)
# 生成带时间戳的报告文件名
timestamp = time.strftime("%Y%m%d_%H%M%S")
report_file = os.path.join(report_dir, f"test_report_{timestamp}.html")
# 运行测试并生成HTML报告
with open(report_file, "wb") as f:
runner = HTMLTestRunner(
stream=f,
title="自动化测试报告",
description="测试执行结果"
)
runner.run(test_suite)
print(f"测试报告已生成: {report_file}")
# 使用示例
run_tests()
2.10 社交媒体自动发布脚本
自动将内容发布到多个社交媒体平台。
python复制import tweepy
import facebook
import schedule
import time
class SocialMediaPoster:
def __init__(self, twitter_keys, facebook_token):
# Twitter认证
auth = tweepy.OAuthHandler(twitter_keys["consumer_key"], twitter_keys["consumer_secret"])
auth.set_access_token(twitter_keys["access_token"], twitter_keys["access_token_secret"])
self.twitter_api = tweepy.API(auth)
# Facebook认证
self.facebook_graph = facebook.GraphAPI(facebook_token)
def post_to_twitter(self, message, image_path=None):
if image_path:
media = self.twitter_api.media_upload(image_path)
self.twitter_api.update_status(status=message, media_ids=[media.media_id])
else:
self.twitter_api.update_status(message)
def post_to_facebook(self, message, image_path=None):
if image_path:
self.facebook_graph.put_photo(image=open(image_path, "rb"), message=message)
else:
self.facebook_graph.put_object("me", "feed", message=message)
def schedule_post(self, platform, message, image_path=None, time_str="09:00"):
if platform.lower() == "twitter":
schedule.every().day.at(time_str).do(self.post_to_twitter, message, image_path)
elif platform.lower() == "facebook":
schedule.every().day.at(time_str).do(self.post_to_facebook, message, image_path)
while True:
schedule.run_pending()
time.sleep(1)
# 使用示例
twitter_keys = {
"consumer_key": "your_consumer_key",
"consumer_secret": "your_consumer_secret",
"access_token": "your_access_token",
"access_token_secret": "your_access_token_secret"
}
poster = SocialMediaPoster(twitter_keys, "your_facebook_token")
poster.schedule_post("twitter", "每日更新内容", time_str="10:00")
poster.schedule_post("facebook", "Facebook每日更新", image_path="post_image.jpg")
3. Python自动化脚本开发技巧
3.1 错误处理与日志记录
健壮的自动化脚本需要完善的错误处理和日志记录机制。以下是一些最佳实践:
python复制import logging
import traceback
def setup_logging(log_file="automation.log"):
logging.basicConfig(
filename=log_file,
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logging.getLogger().addHandler(console)
def safe_execute(func, *args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
logging.error(f"执行失败: {str(e)}")
logging.error(traceback.format_exc())
return None
# 使用示例
setup_logging()
def risky_operation():
# 可能失败的操作
pass
safe_execute(risky_operation)
3.2 配置管理
将配置信息与代码分离,便于维护和部署:
python复制import configparser
import os
def load_config(config_file="config.ini"):
config = configparser.ConfigParser()
if os.path.exists(config_file):
config.read(config_file)
return config
else:
raise FileNotFoundError(f"配置文件不存在: {config_file}")
# config.ini示例内容
"""
[database]
host = localhost
port = 5432
username = admin
password = secret
[email]
smtp_server = smtp.example.com
smtp_port = 587
sender = noreply@example.com
"""
3.3 定时任务执行
使用schedule库实现定时任务:
python复制import schedule
import time
def job():
print("定时任务执行中...")
# 设置定时任务
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
while True:
schedule.run_pending()
time.sleep(1)
对于更复杂的调度需求,可以考虑使用APScheduler:
python复制from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
@scheduler.scheduled_job("interval", minutes=30)
def timed_job():
print("每30分钟执行一次")
@scheduler.scheduled_job("cron", day_of_week="mon-fri", hour=9)
def morning_job():
print("工作日早上9点执行")
scheduler.start()
4. 常见问题与解决方案
4.1 脚本权限问题
在Linux/Unix系统上运行脚本时可能会遇到权限问题。解决方法:
bash复制chmod +x script.py # 添加执行权限
对于需要管理员权限的操作,可以使用sudo或设计更精细的权限控制。
4.2 依赖管理
使用虚拟环境隔离项目依赖:
bash复制python -m venv myenv
source myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows
pip install -r requirements.txt
4.3 跨平台兼容性
处理不同操作系统的路径差异:
python复制import os
# 不好的写法
file_path = "folder\\file.txt" # Windows风格
# 好的写法
file_path = os.path.join("folder", "file.txt") # 跨平台兼容
4.4 长时间运行脚本的稳定性
对于需要长时间运行的脚本:
- 添加异常捕获和自动恢复机制
- 实现日志轮转,避免日志文件过大
- 监控内存使用,防止内存泄漏
- 考虑使用进程管理工具如supervisor
4.5 性能优化技巧
- 对于大量文件操作,使用多线程或异步IO
- 减少不必要的数据库查询,使用缓存
- 批量处理数据而不是逐条处理
- 使用生成器处理大数据集,减少内存占用
python复制# 不好的写法:一次性读取大文件
with open("large_file.txt") as f:
lines = f.readlines() # 可能消耗大量内存
for line in lines:
process(line)
# 好的写法:逐行处理
with open("large_file.txt") as f:
for line in f: # 使用文件迭代器
process(line)
5. 扩展思路与进阶方向
5.1 将脚本打包为可执行文件
使用PyInstaller将Python脚本打包为独立的可执行文件:
bash复制pip install pyinstaller
pyinstaller --onefile script.py
5.2 创建Web界面
使用Flask或Django为脚本添加Web界面:
python复制from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/run-script", methods=["POST"])
def run_script():
data = request.json
# 调用脚本功能
result = your_script_function(data)
return jsonify({"status": "success", "result": result})
if __name__ == "__main__":
app.run(debug=True)
5.3 集成到CI/CD流程
将自动化脚本集成到持续集成流程中,例如GitHub Actions:
yaml复制name: Run Automation Script
on:
schedule:
- cron: "0 9 * * *" # 每天9点运行
workflow_dispatch:
jobs:
run-script:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: "3.9"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run script
run: python your_script.py
5.4 机器学习增强自动化
使用机器学习使脚本更智能:
- 自然语言处理自动分类文档
- 计算机视觉自动识别图像内容
- 预测分析优化任务调度
python复制from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
def auto_categorize_documents(documents, n_categories=5):
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(documents)
model = KMeans(n_clusters=n_categories)
model.fit(X)
return model.labels_
# 使用示例
documents = ["文档1内容", "文档2内容", ...]
categories = auto_categorize_documents(documents)
