Building a Python Weather Alert for Morning Routine Optimization
As the CTO of an AI startup, my days are filled with decision-making, code reviews, and development. Efficiency is key, not just in workflows but also in personal routines. One small yet impactful way to streamline morning routines is by automating the decision of what to wear based on the weather. In this post, I’ll guide you through creating a Python script that sends you a weather alert each morning, helping you choose your attire for the day. (*Note, sure you could use a standard service like Weather Underground, but where’s the fun in that 😜😜)
Setting the Stage: Tools and APIs
We’ll use Python, a versatile language ideal automation. The script will retrieve weather data from an API (Application Programming Interface) and send an email with the weather alert. For weather data, we’ll use the OpenWeatherMap API, which provides comprehensive weather data for locations worldwide. For sending emails, we’ll use the SMTP protocol through Python’s smtplib
.
Step 1: Getting Your API Key
First, sign up at OpenWeatherMap to get your API key. This key allows you to retrieve weather data. Keep this key secure and do not share it publicly.
Step 2: Setting Up Your Python Environment
Ensure you have Python installed on your system. Create a virtual environment and install the necessary packages:
python3 -m venv weather_alert_env
source weather_alert_env/bin/activate
pip install requests
Step 3: Writing the Weather Alert Script
Create a new Python script named weather_alert.py
and open it in your editor (I am using VScode). Here's how to structure the script:
- Import Libraries: We’ll need
requests
for API calls andsmtplib
for sending emails. - Define Constants: Include your OpenWeatherMap API key, your email credentials, and the recipient’s email address.
- Fetch Weather Data: Use the OpenWeatherMap API to get the current weather for your location.
- Compose the Email: Based on the weather data, compose a message advising on what to wear.
- Send the Email: Use SMTP to send the email with the weather alert.
import requests
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Constants
API_KEY = 'your_openweathermap_api_key'
EMAIL_ADDRESS = 'your_email@example.com'
EMAIL_PASSWORD = 'your_email_password'
RECIPIENT_EMAIL = 'recipient_email@example.com'
LOCATION = 'Kirkland,WA,USA'
def fetch_weather(api_key, location):
base_url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric"
response = requests.get(base_url)
return response.json()
def compose_email(weather_data):
weather = weather_data['weather'][0]['main']
temp = weather_data['main']['temp']
advice = "It's a warm day, consider wearing light clothes." if temp > 20 else "It might be chilly, consider wearing a jacket."
message = f"Good morning! Today's weather in {LOCATION}: {weather}, {temp}°C. {advice}"
return message
def send_email(subject, body):
msg = MIMEMultipart()
msg['From'] = EMAIL_ADDRESS
msg['To'] = RECIPIENT_EMAIL
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = SMTP('smtp.example.com', 587)
server.starttls()
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
server.send_message(msg)
server.quit()
weather_data = fetch_weather(API_KEY, LOCATION)
email_body = compose_email(weather_data)
send_email("Today's Weather Alert", email_body)
Step 4: Scheduling the Script
To ensure you receive the weather alert each morning without manually running the script, you can automate its execution using the operating system’s task scheduling features. Below, I’ll show you how to set this up on both Linux/Mac (using Cron) and Windows (using Task Scheduler and PowerShell).
Scheduling on Linux/Mac with Cron
I’m not a Mac or Linux user, but below is a process you could use for scheduling via MacOS or Linux.
Cron is a time-based job scheduler in Unix-like operating systems. To schedule your Python script to run at a specific time daily, follow these steps:
- Open the Terminal.
- Edit the crontab file by running
crontab -e
. This command opens the crontab file in the default editor. - Add a cron job to the crontab file. The format for a cron job is as follows:
* * * * * command to be executeds
- - - - -
| | | | |
| | | | +----- Day of the week (0 - 7) (Sunday=0 or 7)
| | | +------- Month (1 - 12)
| | +--------- Day of the month (1 - 31)
| +----------- Hour (0 - 23)
+------------- Minute (0 - 59)
For example, to run the script every day at 7:00 AM, you would add the following line (assuming your script is located at /path/to/weather_alert.py
and your Python environment is at /path/to/python
)
0 7 * * * /path/to/python /path/to/weather_alert.py
4. Save and exit the editor. The cron job is now set and will run at the scheduled time.
Scheduling on Windows with Task Scheduler
I use windows, so this is the route I took.
Task Scheduler allows you to automate tasks on Windows. To schedule your Python script:
- Open Task Scheduler: Press
Windows + R
, typetaskschd.msc
, and press Enter. - Create a Basic Task: In the Action menu, select
Create Basic Task
. - Follow the Wizard: Give your task a name, for example, “Weather Alert”, and click
Next
. Choose theDaily
trigger, set the start time to your preferred time (e.g., 7:00 AM), and clickNext
. - Start a Program: In the Action step, select
Start a Program
and clickNext
. For the Program/script field, enter the path to your Python executable (e.g.,C:\Python39\python.exe
). In the Add arguments (optional) field, enter the path to your script (e.g.,C:\path\to\weather_alert.py
). ClickNext
. - Finish Setup: Review your settings and click
Finish
.
PowerShell Script to Create a Scheduled Task
Alternatively, you could use PowerShell.
The following PowerShell script creates a scheduled task that runs your Python weather alert script at a specified time each day. Before running this script, ensure you have the paths to your Python executable and your Python script ready.
- Open PowerShell as an Administrator: You need administrative privileges to create a scheduled task.
- Create a New PowerShell Script: Save the following script as
CreateWeatherAlertTask.ps1
, replacing the placeholders with your actual paths and preferred time.
$TaskName = "WeatherAlert"
$TaskDescription = "Runs a Python script to send a daily weather alert email"
$TriggerTime = "07:00" # Set to your preferred time in HH:mm format
$PythonPath = "C:\Path\To\Python.exe" # Replace with the path to your Python executable
$ScriptPath = "C:\Path\To\weather_alert.py" # Replace with the path to your Python script
# Delete the task if it already exists
If (Get-ScheduledTask | Where-Object {$_.TaskName -eq $TaskName}) {
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
}
# Create a trigger for the task
$Trigger = New-ScheduledTaskTrigger -At $TriggerTime -Daily
# Create an action for the task
$Action = New-ScheduledTaskAction -Execute $PythonPath -Argument "`"$ScriptPath`""
# Create the task
Register-ScheduledTask -TaskName $TaskName -Description $TaskDescription -Trigger $Trigger -Action $Action -RunLevel Highest -User "SYSTEM"
Write-Output "Scheduled task '$TaskName' created successfully."power
- Run the PowerShell Script: Navigate to the location of your script in PowerShell, and run it by typing
.\CreateWeatherAlertTask.ps1
and pressing Enter. If you encounter any execution policy restrictions, you can temporarily bypass the policy by running the script withPowershell -ExecutionPolicy Bypass -File .\CreateWeatherAlertTask.ps1
.
This script creates a new scheduled task named “WeatherAlert” that runs your Python weather alert script daily at the time specified in $TriggerTime
. It runs the task using the SYSTEM account at the highest privilege level, ensuring it has the permissions needed to execute successfully.
Remember, running scripts and modifying scheduled tasks require careful consideration of security implications, especially when using elevated permissions. Always ensure your scripts are safe and from trusted sources before executing them with administrative privileges.
Your Python script is now scheduled to run every morning at the time you specified, sending you the daily weather alert to help you choose what to wear.
By automating the execution of your weather alert script, you ensure that you receive timely updates every day without any manual intervention, making your mornings a little easier and more efficient.
Conclusion
With this simple yet effective Python script, you can start each day informed and ready to dress appropriately for the weather. This approach not only saves me time but also introduces the concept of automating routine decisions, allowing me to focus more on other core responsibilities.