Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Python Automation Cookbook
  • Table Of Contents Toc
Python Automation Cookbook

Python Automation Cookbook - Third Edition

By : Jaime Buelta
close
close
Python Automation Cookbook

Python Automation Cookbook

By: Jaime Buelta

Overview of this book

Automating repetitive tasks and integrating systems efficiently becomes increasingly complex as workflows scale. This book helps you solve that problem with practical Python recipes that guide you from foundational automation to advanced, AI-powered workflows. You start by building a strong base in Python automation, exploring tested solutions for file handling, web scraping, APIs, testing, and system operations, and learning how to design reliable automation workflows. The cookbook approach enables you to quickly apply solutions to real problems while building a deeper understanding through hands-on practice. This third edition expands the scope of automation by introducing AI-powered capabilities. You learn how to call AI models within your scripts, use and implement the Model Context Protocol (MCP) for system integration, and design intelligent agents that automate decision-making processes. New chapters provide real-world examples of AI agents in business automation, helping you move beyond scripts to adaptive systems. This book combines practical knowledge with modern techniques to ensure you stay current with evolving automation practices. By the end of this book, you will be able to design, build, and extend Python automation workflows, including AI-driven solutions, to handle complex real-world tasks with confidence.
Table of Contents (20 chapters)
close
close
18
Other Books You May Enjoy
19
Index

Preface

We all spend too much time at work on manual tasks that add relatively little value. Scanning through information sources for a few relevant bits of data, updating the same spreadsheet graph with fresh data over and over, or opening files one by one to find the data we need. Many of these tasks can be automated so that the computer performs most of the work, but perhaps you don't yet feel capable of doing it.

The good news is that now is the best moment to start. The Python language and its ecosystem have grown ever more powerful while remaining approachable. The environment continues to improve, with stronger integrations, richer libraries, and with a vibrant community behind it all.

But the most impactful change since the previous editions of this book has been the rise of AI tools, which have become astonishingly capable within a very short space of time. Their progress over the past year in particular has been remarkable. AI tools can now help you create code, accelerate your learning, and even handle tasks independently.

AI, however, is a multiplier. If your knowledge is solid, it will greatly amplify your abilities. But without clear direction, results will be scattered and unfocused. We will start the book by building our foundation, by way of small, clear recipes that can be adapted to your needs. These building blocks will gradually combine into more complex workflows. While we will note where AI can help us, we will focus first on the capabilities of Python, ensuring predictable, deterministic results. Among other recipes, you will learn to automate common tasks like scraping the web for opportunities, generating spreadsheet reports with graphs, sending automatic emails, receiving text notifications, and running tasks in the background, all while you focus on more important work. Don't underestimate this part! You will be achieving genuinely impressive results.

Then we will build on this foundation by showing you how to work directly with AI models and create your own AI agents that combine some of the earlier recipes. The automations that result are powerful, but we don't shy away from discussing their limitations, caveats, and risks.

Throughout the book we introduce many of the excellent third-party tool options to be found in the rich Python ecosystem. This will inspire your imagination and plant ideas for tackling a wide range of projects by leveraging the available libraries, even those not covered here. There are plenty to choose from!

Although familiarity with Python is helpful, this book is designed for non-programmers. It offers clear, practical recipes, guiding you towards greater proficiency while keeping the focus on real, everyday goals.

Who this book is for

This book is for Python beginners, not necessarily developers, who want to use and expand their knowledge in order to automate tasks and learn how to do so with the help of AI. Most of the examples in the book are aimed at marketing, sales, and other non-tech areas. However, if you have already learnt a little about the Python language, such as its basic concepts, then so much the better.

What this book covers

Chapter 1, Let's Begin Our Automation Journey, presents some content that will be used all through the book. It addresses the 'vibe coding' idea, and explains how to install and manage third-party tools, how to perform effective string manipulation, and how to use command-line arguments. It also introduces you to regular expressions and other methods of text processing.

Chapter 2, Automating Tasks Made Easy, shows how to prepare and automatically run tasks. It covers how to program tasks to be executed when they should, instead of running them manually; how to be notified with the result of a task that's run automatically; and how to be notified if there has been an error in an automated process.

Chapter 3, Building Your First Web Scraping Applications, explores sending web requests to communicate with external websites, including via raw HTML content, structured feeds, and RESTful APIs; and looks at automating a browser to execute steps without manual intervention. It also covers how to process results to extract relevant information.

Chapter 4, Searching and Reading Local Files, explains how to search through local files and directories and analyze the information stored there. You will learn how to filter through relevant files in different encodings and read files in several common formats, such as CSVs, PDFs, Word documents, and even images.

Chapter 5, Generating Fantastic Reports, looks at how to display information given in text format in multiple formats. This includes creating templates to produce text files, as well as creating richly formatted and properly styled Word and PDF documents.

Chapter 6, Fun with Spreadsheets, explores how to read and write spreadsheets in the CSV format, and in Microsoft Excel, including with formatting and charts and using Python inside Excel.

Chapter 7, Cleaning and Processing Data, presents techniques to deal with multiple sources of information and clean up data before processing it. You will learn how to batch-process to speed up working with large amounts of data, including using specific data analysis libraries like Pandas.

Chapter 8, Developing Stunning Graphs, explains how to produce beautiful charts, including common examples such as pie, line, and bar charts, as well as other advanced cases, such as stacked bars and even maps. It also explains how multiple graphs can be combined and styled to generate rich graphics and show relevant information in an understandable format.

Chapter 9, Dealing with Communication Channels, explains how to send messages via multiple channels, using external tools to do the most of the heavy lifting. This chapter goes into sending and receiving emails individually as well as en masse, communicating through SMS messages, and creating a bot in Telegram.

Chapter 10, Why Not Automate Your Marketing Campaign?, combines the different recipes included in previous chapters to generate a full marketing campaign, including steps such as detecting an opportunity, generation of promotions, communication to potential customers, and analyzing and reporting sales produced by promotions. This chapter shows how to combine different elements to create powerful systems.

Chapter 11, Calling AI Models, shows you how to integrate an AI model to work with text and images into your code, both from an externally hosted provider as well as using a local model.

Chapter 12, Adding Tools to GenAI, discusses how to enhance AI models' abilities to interact with different tools, including the definition of MCP servers to multiply the capacities of the models by making them able to perform specific actions.

Chapter 13, Building AI Agents for Business Automation, explores the ReAct architecture to create AI Agents capable of executing complex tasks by combining multiple tools.

Chapter 14, Real-World AI Example, combines all the techniques and lessons from the previous chapters to generate a full example of an agent to perform a complex task, and discusses the implications in terms of security, performance, costs, and others. These are important elements for real work!

Chapter 15, Automatic Testing Routines, explores the write and execute tests to verify that code is behaving as expected. The pytest framework is presented and common scenarios for working effectively with tests are discussed.

Chapter 16, Debugging Techniques, features different methods and tips for helping with the debugging process to ensure the quality of your software. It leverages the great introspection capabilities of Python and its out-of-the-box debugging tools for fixing problems and producing solid automated software.

To get the most out of this book

  • Before reading this book, readers need to know the basics of the Python language. We do not assume that the reader is an expert in the language.
  • The reader needs to know how to input commands in the command line (Terminal, Bash, or equivalent).
  • To understand the code in this book you need a text editor, which will enable you to read and edit the code. Use an IDE that supports the Python language, such as PyCharm.

Download the example code files

The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Python-Automation-Cookbook-Third-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/gbp/9781806702893.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: "Finally, the meeting_preparation_agent.py script is the one that orchestrates everything."

A block of code is set as follows:

def main(base_url, to_search):
    checked_links = set()
    to_check = [base_url]
    max_checks = 10

Any command-line input or output is written as follows:

>>> result = requests.get('https://jsonplaceholder.typicode.com/posts')

Bold: Indicates a new term, an important word, or words that you see on the screen. For instance, words in menus or dialog boxes appear in the text like this. For example: "This is the specification of the standard output (stdout)"

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book or have any general feedback, please email us at [email protected] and mention the book's title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit http://www.packt.com/submit-errata, click Submit Errata, and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packt.com/.

Share your thoughts

Once you've read Python Automation Cookbook, Third Edition, we'd love to hear your thoughts! Scan the QR code below to go straight to the Amazon review page for this book and share your feedback.

Image

https://packt.link/r/1806702894

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Python Automation Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon