Eight Practical Python Automation Scripts for Everyday Tasks
This article presents eight ready‑to‑use Python scripts that automate common tasks such as image and video processing, scheduled email sending, PDF‑to‑image conversion, API data fetching, battery monitoring, testing with pytest, and file backup‑sync, complete with code examples.
This article introduces a collection of eight Python automation scripts designed to simplify routine tasks and improve productivity.
1. Image Optimization
The script uses the Pillow library (PIL) to crop, resize, flip, rotate, compress, blur, sharpen, adjust brightness and contrast, and apply filters to images.
# Image optimization
from PIL import Image, ImageFilter, ImageOps, ImageEnhance
# Load image
im = Image.open("Image1.jpg")
# Crop image
im = im.crop((34, 23, 100, 100))
# Resize image
im = im.resize((50, 50))
# Horizontal flip
im = im.transpose(Image.FLIP_LEFT_RIGHT)
# Rotate image 360 degrees
im = im.rotate(360)
# Compress image
im.save("Image1.jpg", optimize=True, quality=90)
# Apply blur
im = im.filter(ImageFilter.BLUR)
# Apply sharpen
im = im.filter(ImageFilter.SHARPEN)
# Adjust brightness
enhancer = ImageEnhance.Brightness(im)
im = enhancer.enhance(1.5)
# Adjust contrast
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(1.5)
# Add filters
im = ImageOps.grayscale(im)
im = ImageOps.invert(im)
im = ImageOps.posterize(im, 4)
# Save optimized image
im.save("Image1.jpg")2. Video Optimization
This script leverages the MoviePy library to trim, speed up, add audio, reverse, merge clips, apply visual effects, and insert images into videos.
# Video optimizer
import moviepy.editor as pyedit
# Load video
video = pyedit.VideoFileClip("vid.mp4")
# Trim video
vid1 = video.subclip(0, 10)
vid2 = video.subclip(20, 40)
final_vid = pyedit.concatenate_videoclips([vid1, vid2])
# Speed up video
final_vid = final_vid.speedx(2)
# Add audio
aud = pyedit.AudioFileClip("bg.mp3")
final_vid = final_vid.set_audio(aud)
# Reverse video
final_vid = final_vid.fx(pyedit.vfx.time_mirror)
# Merge two videos
vid1 = pyedit.VideoFileClip("vid1.mp4")
vid2 = pyedit.VideoFileClip("vid2.mp4")
final_vid = pyedit.concatenate_videoclips([vid1, vid2])
# Add VFX
vid1 = final_vid.fx(pyedit.vfx.mirror_x)
vid2 = final_vid.fx(pyedit.vfx.invert_colors)
final_vid = pyedit.concatenate_videoclips([vid1, vid2])
# Add images
img1 = pyedit.ImageClip("img1.jpg")
img2 = pyedit.ImageClip("img2.jpg")
final_vid = pyedit.concatenate_videoclips([img1, img2])
# Save final video
final_vid.write_videofile("final.mp4")3. Scheduled Email Sending
The script combines smtplib and schedule to send emails automatically at a specified time each day.
# Email scheduler
import smtplib
import schedule
import time
def send_email():
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "your_email_password"
subject = "自动化邮件"
body = "这是使用Python发送的自动化邮件。"
message = f"Subject: {subject}\n\n{body}"
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
# Send every day at 08:00
schedule.every().day.at("08:00").do(send_email)
while True:
schedule.run_pending()
time.sleep(1)4. PDF to Image Conversion
Using the fitz (PyMuPDF) module, this script converts each page of a PDF file into separate PNG images.
# PDF to image conversion
import fitz
def pdf_to_images(pdf_file):
doc = fitz.open(pdf_file)
for page in doc:
pix = page.get_pixmap()
output = f"page{page.number}.png"
pix.writePNG(output)
pdf_to_images("test.pdf")5. API Data Retrieval
The script demonstrates GET and POST requests with urllib3 to fetch data from an API and to submit data to a test endpoint.
# API data fetching
import urllib3
# GET request
url = "https://api.github.com/users/psf/repos"
http = urllib3.PoolManager()
response = http.request('GET', url)
print("Status:", response.status)
print("Response:", response.data)
# POST request
url = "https://httpbin.org/post"
response = http.request('POST', url, fields={'hello': 'world'})
print("Status:", response.status)6. Battery Indicator
This utility monitors battery level with psutil and shows a desktop notification via plyer when the charge drops below a threshold.
# Battery notifier
from plyer import notification
import psutil
from time import sleep
while True:
battery = psutil.sensors_battery()
life = battery.percent
if life < 50:
notification.notify(
title="电池低电量",
message="请连接电源",
timeout=10
)
sleep(50)7. Automated Testing with Pytest
The example shows a simple function and a set of pytest test cases to verify its correctness.
# Pytest automation
import pytest
# Function to test
def add_numbers(x, y):
return x + y
# Test cases
def test_addition():
assert add_numbers(1, 2) == 3
assert add_numbers(-1, 1) == 0
assert add_numbers(0, 0) == 0
assert add_numbers(10, 5) == 15
if __name__ == "__main__":
pytest.main()8. File Backup and Synchronization
This script walks through a source directory, copies files to a backup location, and removes any files from the backup that no longer exist in the source.
# File backup and sync script
import os
import shutil
def backup_and_sync(source_folder, backup_folder):
for root, _, files in os.walk(source_folder):
for file in files:
source_path = os.path.join(root, file)
backup_path = os.path.join(backup_folder, root.replace(source_folder, ""), file)
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
shutil.copy2(source_path, backup_path)
# Remove files in backup that are missing from source
for root, _, files in os.walk(backup_folder):
for file in files:
backup_path = os.path.join(root, file)
source_path = os.path.join(source_folder, root.replace(backup_folder, ""), file)
if not os.path.exists(source_path):
os.remove(backup_path)
source_folder = "path/to/source/folder"
backup_folder = "path/to/backup/folder"
backup_and_sync(source_folder, backup_folder)These scripts provide a quick start for automating repetitive tasks, allowing you to focus on higher‑level work.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.