Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Python Automation Cookbook
Python Automation Cookbook

Python Automation Cookbook: 75 Python automation recipes for web scraping; data wrangling; and Excel, report, and email processing , Second Edition

Arrow left icon
Profile Icon Jaime Buelta
Arrow right icon
S$32.99 S$47.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (16 Ratings)
eBook May 2020 526 pages 2nd Edition
eBook
S$32.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial
Arrow left icon
Profile Icon Jaime Buelta
Arrow right icon
S$32.99 S$47.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (16 Ratings)
eBook May 2020 526 pages 2nd Edition
eBook
S$32.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial
eBook
S$32.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Python Automation Cookbook

Automating Tasks Made Easy

To properly automate tasks, we need a way to make them execute automatically at the proper times. A task that needs to be started manually is not really fully automated.

However, in order to be able to leave them running in the background while worrying about more pressing issues, the task will need to be adequate to run in fire-and-forget mode. We should be able to monitor that it executes correctly, be sure that we capture relevant information (such as receiving notifications if something interesting arises), and know whether there have been any errors while running it.

Ensuring that a piece of software runs consistently with high reliability is actually a very big deal. It is one area that, in order to be done properly, requires specialized knowledge and staff, who typically go by the names of sysadmin, operations, or SRE (Site Reliability Engineering). Big operations, such as Amazon and Google, require huge investment in ensuring...

Preparing a task

It all starts with defining precisely the work that needs to be executed, and designing it in a way that doesn't require human intervention to run.

Some ideal characteristic points are as follows:

  1. Single, clear entry point: No confusion on how to start the task.
  2. Clear parameters: If there are any parameters, they should be as explicit as possible.
  3. No interactivity: Stopping the execution to request information from the user is not possible.
  4. The result should be stored: In order to be checked at a different time than when it runs.
  5. Clear result: When we oversee the execution of a program ourselves, we can accept more verbose results, such as unlabeled data or extra debugging information. However, for an automated task, the final result should be as concise and to the point as possible.
  6. Errors should be logged: To analyze what went wrong.

A command-line program has a lot of those characteristics already...

Setting up a cron job

Cron is an old-fashioned but reliable way of executing commands. It has been around since the 1970s in Unix, and it's an old favorite in system administration to perform maintenance tasks such as freeing up disk space, rotating log files, making backups, and other common, repetitive operations.

This recipe is Unix and Unix-like operating systems specific, so it will work in Linux and macOS. While it's possible to schedule a task in Windows, it's very different and uses Task Scheduler, which won't be described here. If you have access to a Linux server, this can be a good way of scheduling periodic tasks.

The main advantages are as follows:

  • It's present in virtually all Unix or Linux systems and configured to run automatically.
  • It's easy to use, although a little deceptive at first.
  • It's well known. Almost anyone involved with admin tasks will have a general idea of how to use it.
  • It allows...

Capturing errors and problems

An automated task's main characteristic is its fire-and-forget quality. We are not actively looking at the result, but making it run in the background.

Most of the recipes in this book deal with external information, such as web pages or other reports, so the likelihood of finding an unexpected problem when running it is high. This recipe will present an automated task that will safely store unexpected behaviors in a log file that can be checked afterward.

Getting ready

As a starting point, we'll use a task that will divide two numbers, as described in the command line.

This task is very similar to the one presented in step 5 of How it works for the Preparing a task recipe, earlier this chapter. However, instead of multiplying two numbers, we'll divide them.

How to do it...

  1. Create the task_with_error_handling_step1.py file, as follows:
    import argparse
    import sys
    def main(number, other_number...

Sending email notifications

Email has become an inescapable tool for everyday use. It's arguably the best place to send a notification if an automated task has detected something. On the other hand, email inboxes are already too full up with spam messages, so be careful.

Spam filters are also a reality. Be careful with whom to send emails to and the number of emails to be sent. An email server or address can be labeled as a spam source, and all emails may be quietly dropped by the internet.

This recipe will show you how to send a single email using an existing email account.

This approach is viable for spare emails sent to a couple of people, as a result of an automated task, but no more than that. Refer to Chapter 9, Dealing with Communication Channels, for more ideas on how to send emails, including groups.

Getting ready

For this recipe, we require a valid email account set up, which includes the following:

  • A valid email server using SMTP...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Automate integral business processes such as report generation, email marketing, and lead generation
  • Explore automated code testing and Python’s growth in data science and AI automation in three new chapters
  • Understand techniques to extract information and generate appealing graphs, and reports with Matplotlib

Description

In this updated and extended version of Python Automation Cookbook, each chapter now comprises the newest recipes and is revised to align with Python 3.8 and higher. The book includes three new chapters that focus on using Python for test automation, machine learning projects, and for working with messy data. This edition will enable you to develop a sharp understanding of the fundamentals required to automate business processes through real-world tasks, such as developing your first web scraping application, analyzing information to generate spreadsheet reports with graphs, and communicating with automatically generated emails. Once you grasp the basics, you will acquire the practical knowledge to create stunning graphs and charts using Matplotlib, generate rich graphics with relevant information, automate marketing campaigns, build machine learning projects, and execute debugging techniques. By the end of this book, you will be proficient in identifying monotonous tasks and resolving process inefficiencies to produce superior and reliable systems.

Who is this book for?

Python Automation Cookbook - Second Edition is for developers, data enthusiasts or anyone who wants to automate monotonous manual tasks related to business processes such as finance, sales, and HR, among others. Working knowledge of Python is all you need to get started with this book.

What you will learn

  • Learn data wrangling with Python and Pandas for your data science and AI projects
  • Automate tasks such as text classification, email filtering, and web scraping with Python
  • Use Matplotlib to generate a variety of stunning graphs, charts, and maps
  • Automate a range of report generation tasks, from sending SMS and email campaigns to creating templates, adding images in Word, and even encrypting PDFs
  • Master web scraping and web crawling of popular file formats and directories with tools like Beautiful Soup
  • Build cool projects such as a Telegram bot for your marketing campaign, a reader from a news RSS feed, and a machine learning model to classify emails to the correct department based on their content
  • Create fire-and-forget automation tasks by writing cron jobs, log files, and regexes with Python scripting

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 29, 2020
Length: 526 pages
Edition : 2nd
Language : English
ISBN-13 : 9781800202597
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : May 29, 2020
Length: 526 pages
Edition : 2nd
Language : English
ISBN-13 : 9781800202597
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 256.97
Modern Python Cookbook
S$128.99
Python Automation Cookbook
S$59.99
40 Algorithms Every Programmer Should Know
S$67.99
Total S$ 256.97 Stars icon

Table of Contents

15 Chapters
Let's Begin Our Automation Journey Chevron down icon Chevron up icon
Automating Tasks Made Easy Chevron down icon Chevron up icon
Building Your First Web Scraping Application Chevron down icon Chevron up icon
Searching and Reading Local Files Chevron down icon Chevron up icon
Generating Fantastic Reports Chevron down icon Chevron up icon
Fun with Spreadsheets Chevron down icon Chevron up icon
Cleaning and Processing Data Chevron down icon Chevron up icon
Developing Stunning Graphs Chevron down icon Chevron up icon
Dealing with Communication Channels Chevron down icon Chevron up icon
Why Not Automate Your Marketing Campaign? Chevron down icon Chevron up icon
Machine Learning for Automation Chevron down icon Chevron up icon
Automatic Testing Routines Chevron down icon Chevron up icon
Debugging Techniques Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(16 Ratings)
5 star 56.3%
4 star 6.3%
3 star 18.8%
2 star 0%
1 star 18.8%
Filter icon Filter
Top Reviews

Filter reviews by




siebo Jun 11, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book shows how Python can be applied to many common workflows. It covers tasks like file manipulation, text processing, structured data, graphing and reporting, and marketing automation. The code examples are written in modern, well-structured Python code. Reading the book sequentially gives you a tour of some of the things can do with Python. It helps you recognize opportunities to automate your work, using the language, and helps build up your abilities to confidently use Python this way. It can also be used as a Cookbook, where you refer to specific chapters when working with particular use cases. I think this book is approachable even for people who are new to Python. I'd also recommend it to developers who already work with Python, for example with a web framework, and want to expand their knowledge into using the language to automate their daily workflows.
Amazon Verified review Amazon
Steven Klassen Jun 12, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Disclaimer: I was offered a review copy by the publisher to write an honest review.I skimmed through this book over the course of a week paying close attention to the code samples. The writing is really very good and didn't set off any of my grammar alarms that are constantly waiting in the background when I'm reading anything. That made the technical bits a lot more enjoyable.There were a lot of examples that were light and that you could go through from start to finish without getting mired in complicated logic. I didn't find any issues with the code itself which was also nice.If I had to offer a critique for a 2nd edition (if it remains a cookbook style offering) it would be to maybe explain less and show more. While the information in this one was really well written it could have almost dropped cookbook from the title and still been worth its salt.
Amazon Verified review Amazon
James Anzalone Jun 12, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Chapters are very well organized, following a coherent sequence. Although the book has 500+ pages, the way that is structured, in little doses, makes it easier to follow and be focused. Sections like How to do it and How it works help the reader showing all the necessary steps.I love the functionality of the book, with everyday examples like ordering a pizza, how to create a report about watched movies or how to create a CSV spreadsheet, the book is more interesting. Although the book is created for people with a knowledge about Python, it has a lot of information for a lower level reader. ​
Amazon Verified review Amazon
Viktor Kis Jun 11, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Really appreciate any book that starts off driving home the importance of setting virtual environments properly. Yes, a lot of information now days can be searched online, but if you are here, you are willing to chip in a little for a fresh set of neatly laid out concepts – and this book is just that. It is a great compilation of relatable example driven concepts. Regular expression, argument parsing, logging, directory manipulation, reading txt/pdf/image/csv/word/excel files are all bread and butter now days and if any of these topics daunted you, this book gives you a nice high-level intro into them. The web sections were great for me who has really only scrapped the web, I was exposed to other ideas such as automated emails and text messages. Although you don’t have to read the book chapter by chapter, I would have preferred to put the testing section up front to drive test driven development home a bit more. Overall it was a great read – thanks for collecting these ideas/examples and contributing back to the python community!
Amazon Verified review Amazon
Stephan Miller Jun 22, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book has a lot of information. First it shows you how to set up a Python environment for automation, including installing Python, setting up cron jobs to run your tasks on schedule, and adding notifications so you can get details on your jobs delivered to your email.And then it gets interesting. This book differs slightly from other cookbooks I have read that just list a bunch of small coding examples to do specific things. These recipes build on each other and can be mixed and matched to automate a process you are doing manually.The topics covered are web scraping, file processing, report generation, spreadsheet manipulation, data processing and cleaning, graph and chart generation, communication, marketing automation, machine learning, code testing and debugging. You will definitely find enough examples here to automate any process you may have and free up time.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.