Python Scripts that Pack a Punch: Volume 1
Five outstanding Python scripts that will revolutionize your workflow and help you save a tonne of time and effort are presented to you in this first volume.
File Organizer:
A script that searches a given directory and sorts files into distinct folders according to their extensions. This can maintain the orderly organization of your files.
import os # Import os library
import shutil # Import shutil library
def arrange_files(directory): # arrange_files function
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] # List all files in directory
for f in files: # iterate over the files in directory
file_extension = os.path.splitext(f)[1] # split the file name and extension
folder_path = os.path.join(directory, file_extension[1:].upper() + "_Files") # generate path of folder where file needs to be moved
if not os.path.exists(folder_path): # check if folder path exists or not
os.makedirs(folder_path) # create directories to the path
original_file_path = os.path.join(directory, f) # generate path of file to be moved
new_file_path = os.path.join(folder_path, f) # generate path of new location where file needs to be moved
shutil.move(original_file_path, new_file_path) # move the file from original location to new location
print("Success!") # print message on console
dir_to_organize = "/root/foo/bar" # initialize variable with path of directory
arrange_files(dir_to_organize) # call arrange_files function
Website Availability Checker:
A script that checks the status of a list of websites on a regular basis and notifies users through email if any of the websites are unavailable.
import time # import time library
import smtplib # import smtplib library
import requests # import requests library
from email.mime.text import MIMEText # import MIMEText class
from email.mime.multipart import MIMEMultipart # import MIMEMultipart class
websites_list = [ # A list of websites to be monitored
"https://www.example1.com",
]
sender_email = "sender_email@example.com" # sender email address
receiver_email = "recipient_email@yexample.com" # receiver email address
password = "sender_email_password" # sender email password
smtp_server = "smtp.example.com" # SMTP server address
smtp_port = 587 # SMTP server port
def send_email(email_subject, body): # function to send an email
email_message = MIMEMultipart() # Initialize MIMEMultipart class
email_message["From"] = sender_email # Setting email sender address
email_message["To"] = receiver_email # Setting email receiver address
email_message["Subject"] = email_subject # Setting email subject
email_message.attach(MIMEText(body, "plain")) # Set email body
with smtplib.SMTP(smtp_server, smtp_port) as email_server: # Establish a connection with an email server
email_server.starttls() # Start a TLS session
email_server.login(sender_email, password) # Login to the server
email_server.sendmail(sender_email, receiver_email, email_message.as_string()) # Send the email
def check_website_availability(): # A function to check for website availablity
for website in websites_list: # Looping through websites
try: # try block
site_response = requests.get(website) # Get the page response
if site_response.status_code != 200: # Check for the status code
send_email(f"{website} Down", f"Dear foo, The website {website} is down.") # Send an email if site is down
except requests.exceptions.RequestException: # Check if there is an exception
send_email(f"{website} Down", f"The website {website} is down.") # Send an email if site is down
check_website_availability() # Check website availability
while True: # Run forever
check_website_availability() # Check website availability
time.sleep(300) # 5 minutes # Wait for 5 minutes
System Monitoring:
A script that keeps track of your system’s performance and notifies you of any irregularities. By automating the monitoring procedure, keeping tabs on resource utilisation, and receiving notifications, you can make sure your system is always up and running.
import psutil # import psutil library
CPU_PERCENTAGE_THRESHOLD = 90 # Define constant CPU_PERCENTAGE_THRESHOLD with value 90
MEMORY_PERCENTAGE_THRESHOLD = 90 # Define constant MEMORY_PERCENTAGE_THRESHOLD with value 90
DISK_PERCENTAGE_THRESHOLD = 90 # Define constant DISK_PERCENTAGE_THRESHOLD with value 90
def monitor_system(): # Function to monitor system performance
cpu_percentage = psutil.cpu_percent(interval=1) # get the cpu usage for 1 second
if cpu_percentage > CPU_PERCENTAGE_THRESHOLD: # check if cpu usage is greater than threshold
print("High CPU Usage", f"CPU usage is {cpu_percentage}%") # print message on console
device_memory = psutil.virtual_memory() # get the system memory usage
memory_percentage = device_memory.percent # get the percentage of memory usage
if memory_percentage > MEMORY_PERCENTAGE_THRESHOLD: # check if memory usage is greater than threshold
print("High Memory Usage", f"Memory usage is {memory_percentage}%") # print message on console
disk = psutil.disk_usage("/") # get the disk usage
disk_percentage = disk.percent # get the percentage of disk usage
if disk_percentage > DISK_PERCENTAGE_THRESHOLD: # check if disk usage is greater than threshold
print("High Disk Usage", f"Disk usage is {disk_percentage}%") # print message on console
while True: # Run the program continuously
monitor_system() # monitor system performance
You may optimise resource use, streamline your tasks, and proactively deal with future problems thanks to these Python scripts. Experience their efficiency by integrating them into your workflow.
A future edition of Python Scripts that Pack a Punch will cover further scripts that improve productivity and efficiency, so stay tuned.
Coding is fun!