
16 Python Scripting Techniques for Automation
Python is a powerful and versatile language that can be used for a wide range of automation tasks, from simple file management to complex data analysis. In this article, we’ll explore 16 Python scripting techniques for automation that you can use in your projects.
1. Automating File Management
You can use Python’s os
module to automate file management tasks such as copying, moving, and deleting files.
“`python
import os
Copy a file from one directory to another
src = ‘source.txt’
dst = ‘destination.txt’
os.system(f’cp {src} {dst}’)
Move a file from one directory to another
src = ‘source.txt’
dst = ‘destination/’
os.system(f’mv {src} {dst}’)
“`
2. Automating System Tasks
You can use Python’s subprocess
module to automate system tasks such as running shell commands and interacting with the terminal.
“`python
import subprocess
Run a shell command and capture its output
cmd = ‘ls -l’
output = subprocess.check_output(cmd, shell=True).decode(‘utf-8’)
print(output)
“`
3. Using Regular Expressions
You can use Python’s re
module to work with regular expressions, which are powerful patterns used to match and manipulate strings.
“`python
import re
Find all email addresses in a string
email_pattern = r’\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b’
text = ‘Contact me at john.doe@example.com or jane.smith@example.com’
emails = re.findall(email_pattern, text)
print(emails)
“`
4. Parsing CSV and JSON Files
You can use Python’s csv
and json
modules to parse CSV and JSON files, respectively.
“`python
import csv
Parse a CSV file
with open(‘data.csv’, ‘r’) as f:
reader = csv.reader(f)
for row in reader:
print(row)
import json
Parse a JSON file
with open(‘data.json’, ‘r’) as f:
data = json.load(f)
print(data)
“`
5. Using the requests
Library
You can use Python’s requests
library to make HTTP requests and interact with web servers.
“`python
import requests
Make a GET request
url = ‘https://www.example.com’
response = requests.get(url)
print(response.text)
Make a POST request
url = ‘https://www.example.com’
data = {‘key’: ‘value’}
response = requests.post(url, data=data)
print(response.text)
“`
6. Automating Email Sending
You can use Python’s smtplib
library to automate email sending using SMTP servers.
“`python
import smtplib
Send an email using Gmail
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(‘your_email@gmail.com’, ‘your_password’)
msg = ‘Hello, world!’
server.sendmail(‘your_email@gmail.com’, ‘recipient@example.com’, msg)
server.quit()
“`
7. Using the schedule
Library
You can use Python’s schedule
library to schedule tasks to run at specific times or intervals.
“`python
import schedule
import time
def job():
print(‘Hello, world!’)
Schedule a task to run every hour
schedule.every(1).hours.do(job)
while True:
schedule.run_pending()
time.sleep(1)
“`
8. Automating PDF Generation
You can use Python’s fpdf
library to automate PDF generation from HTML templates.
“`python
from fpdf import FPDF
Create a PDF document
pdf = FPDF()
pdf.add_page()
pdf.set_font(‘Arial’, ‘B’, 16)
pdf.cell(0, 10, ‘Hello, world!’, ln=True, align=’L’)
pdf.output(‘hello.pdf’, ‘F’)
“`
9. Using the schedule
Library with Date and Time
You can use Python’s datetime
library to schedule tasks based on specific dates and times.
“`python
import datetime
def job():
print(‘Hello, world!’)
Schedule a task to run at 10:00 AM every day
while True:
now = datetime.datetime.now()
if now.hour == 10 and now.minute == 0:
job()
“`
10. Automating Text Messaging
You can use Python’s twilio
library to automate text messaging using Twilio’s SMS API.
“`python
from twilio.rest import Client
Create a Twilio client
account_sid = ‘your_account_sid’
auth_token = ‘your_auth_token’
client = Client(account_sid, auth_token)
def send_message():
message = client.messages.create(
body=’Hello, world!’,
from_=’your_twilio_phone_number’,
to=’recipient_phone_number’
)
print(message.sid)
“`
11. Using the schedule
Library with Specific Time Intervals
You can use Python’s schedule
library to schedule tasks based on specific time intervals.
“`python
import schedule
def job():
print(‘Hello, world!’)
Schedule a task to run every hour
schedule.every(1).hours.do(job)
while True:
schedule.run_pending()
time.sleep(1)
“`
12. Automating Task Management
You can use Python’s trello
library to automate task management using Trello boards.
“`python
from trello import Board, List
Create a Trello board client
api_key = ‘your_api_key’
board_id = ‘your_board_id’
client = Board(api_key, board_id)
def create_card():
list_id = ‘your_list_id’
card_name = ‘Hello, world!’
client.lists[list_id].add_card(card_name)
“`
13. Using the schedule
Library with Custom Intervals
You can use Python’s schedule
library to schedule tasks based on custom intervals.
“`python
import schedule
def job():
print(‘Hello, world!’)
Schedule a task to run every 3 days and 10 hours
schedule.every(3).days.at(“10:00”).do(job)
while True:
schedule.run_pending()
time.sleep(1)
“`
14. Automating Task Prioritization
You can use Python’s redmine
library to automate task prioritization using Redmine tasks.
“`python
from redmine import Project, Issue
Create a Redmine project client
api_key = ‘your_api_key’
project_id = ‘your_project_id’
client = Project(api_key, project_id)
def create_issue():
subject = ‘Hello, world!’
description = ‘This is an issue.’
client.issues.create(subject, description)
“`
15. Using the schedule
Library with Specific Dates
You can use Python’s datetime
library to schedule tasks based on specific dates.
“`python
import datetime
def job():
print(‘Hello, world!’)
Schedule a task to run on January 1st every year
while True:
now = datetime.datetime.now()
if now.month == 1 and now.day == 1:
job()
“`
16. Automating Task Escalation
You can use Python’s slack
library to automate task escalation using Slack channels.
“`python
from slack import WebClient
Create a Slack client
api_token = ‘your_api_token’
client = WebClient(api_token)
def send_message():
channel_id = ‘your_channel_id’
message = ‘Hello, world!’
client.chat_postMessage(channel=channel_id, text=message)
“`
In conclusion, Python is an incredibly versatile language that can be used for a wide range of automation tasks. By mastering these 16 Python scripting techniques for automation, you’ll be able to automate various tasks and workflows with ease, saving you time and effort in the process.