Home > Backend Development > Python Tutorial > How to Automate Everyday Tasks with Python (Part 2)

How to Automate Everyday Tasks with Python (Part 2)

DDD
Release: 2024-10-19 06:15:01
Original
867 people have browsed it

How to Automate Everyday Tasks with Python (Part 2)

Author: Trix Cyrus

Waymap Pentesting tool: Click Here
TrixSec Github: Click Here

In Part 1, we explored how to use Python to automate file management, web scraping, sending emails, Google Sheets, and system monitoring. In Part 2, we will continue by covering more advanced tasks like automating APIs, scheduling scripts, and integrating automation with third-party services.

7. Automating API Requests

Many web services provide APIs to interact with their platforms programmatically. Using the requests library, you can easily automate tasks like fetching data from APIs, posting updates, or performing CRUD operations on cloud services.

import requests

# OpenWeatherMap API configuration
api_key = 'your_api_key'
city = 'New York'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'

# Send a GET request to fetch weather data
response = requests.get(url)
data = response.json()

# Extract temperature information
temperature = data['main']['temp']
weather = data['weather'][0]['description']

print(f"Temperature: {temperature}°K")
print(f"Weather: {weather}")
Copy after login
Copy after login

This script fetches the current weather data for a specified city from the OpenWeatherMap API and displays it.

8. Scheduling Tasks with Python

Sometimes you need to automate tasks to run at specific times or intervals. Python's schedule library makes it easy to set up jobs that run automatically at certain times.

import schedule
import time

# Task function to be executed
def task():
    print("Executing scheduled task...")

# Schedule the task to run every day at 9 AM
schedule.every().day.at("09:00").do(task)

# Keep the script running to check the schedule
while True:
    schedule.run_pending()
    time.sleep(1)
Copy after login
Copy after login

This script schedules a task to run every day at 9 AM, using a simple scheduling loop to keep the task running.

9. Automating Database Operations

Python can be used to interact with databases, automate data entry, and perform operations like reading, updating, and deleting records. The sqlite3 module allows you to manage SQLite databases, while other libraries (like psycopg2 or MySQLdb) work with PostgreSQL and MySQL.

import sqlite3

# Connect to SQLite database
conn = sqlite3.connect('tasks.db')

# Create a cursor object to execute SQL commands
cur = conn.cursor()

# Create a table for storing tasks
cur.execute('''CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, task_name TEXT, status TEXT)''')

# Insert a new task
cur.execute("INSERT INTO tasks (task_name, status) VALUES ('Complete automation script', 'Pending')")

# Commit changes and close the connection
conn.commit()
conn.close()
Copy after login

This script creates an SQLite database, adds a "tasks" table, and inserts a new task into the database.

10. Automating Excel File Management

Python, along with the openpyxl or pandas libraries, can be used to automate reading, writing, and modifying Excel files. This is especially useful for automating data analysis and reporting tasks.

import pandas as pd

# Read Excel file
df = pd.read_excel('data.xlsx')

# Perform some operation on the data
df['Total'] = df['Price'] * df['Quantity']

# Write the modified data back to a new Excel file
df.to_excel('updated_data.xlsx', index=False)
Copy after login

This script reads an Excel file, performs a calculation on the data, and writes the updated data to a new file.

11. Automating Browser Interactions with Selenium

Using Selenium, Python can automate interactions with web browsers such as logging into accounts, filling forms, and performing repetitive web tasks.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Set up the browser driver
driver = webdriver.Chrome()

# Open the login page
driver.get('https://example.com/login')

# Locate the username and password fields, fill them in, and log in
username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')
username.send_keys('your_username')
password.send_keys('your_password')
password.send_keys(Keys.RETURN)

# Close the browser
driver.quit()
Copy after login

This script opens a web browser, navigates to a login page, fills in the credentials, and logs in automatically.

12. Automating Cloud Services

Python integrates well with cloud services like AWS, Google Cloud, and Azure. Using the boto3 library, you can automate tasks like managing S3 buckets, EC2 instances, and Lambda functions in AWS.

import requests

# OpenWeatherMap API configuration
api_key = 'your_api_key'
city = 'New York'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'

# Send a GET request to fetch weather data
response = requests.get(url)
data = response.json()

# Extract temperature information
temperature = data['main']['temp']
weather = data['weather'][0]['description']

print(f"Temperature: {temperature}°K")
print(f"Weather: {weather}")
Copy after login
Copy after login

This script connects to AWS S3, lists all buckets, creates a new bucket, and uploads a file to it.

13. Automating PDF Manipulation

Using the PyPDF2 library, Python can automate tasks like merging, splitting, and extracting text from PDF files.

import schedule
import time

# Task function to be executed
def task():
    print("Executing scheduled task...")

# Schedule the task to run every day at 9 AM
schedule.every().day.at("09:00").do(task)

# Keep the script running to check the schedule
while True:
    schedule.run_pending()
    time.sleep(1)
Copy after login
Copy after login

This script merges multiple PDF files into a single file.

~Trixsec

The above is the detailed content of How to Automate Everyday Tasks with Python (Part 2). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template