22,99 €
Streamline Your Workflow and Boost Productivity with Python Automation
In today's workplaces, there's a high demand for know-how on the Python programming language, especially for writing time-saving scripts that can simplify routine work tasks. Python Automation For Dummies delivers, with simple explanations of how you can use Python to automatically wrangle data files, manage media files, create shortcuts, find and organize web data, and even analyze social media for trends. With this easy-to-follow Dummies guide, you can upskill, expand your productivity, and speed up the process of generating data-driven insights. You'll even learn to enhance your Python automations with AI, for workflows that are faster and smarter.
This is a great Dummies resource for Python developers interested in applying the popular coding language to make workflows more efficient.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 443
Veröffentlichungsjahr: 2025
Cover
Table of Contents
Title Page
Copyright
Introduction
About This Book
Foolish Assumptions
Icons Used in This Book
Beyond the Book
Where to Go from Here
Part 1: Getting Started with Python Automation
Chapter 1: Automating with Python
Choosing a Programming Language
Understanding Python Syntax
Getting Python
Chapter 2: Choosing a Code Editor
Installing VS Code
Installing Python Extensions
Creating a Folder for a New Project
Using Virtual Environments
Installing Modules
Writing and Running Python Scripts
Chapter 3: Python Basics for Automation
Understanding Python Comments
Mastering Variables and Data Types
Formatting Output
Dealing with Dates and Times
Manipulating Data with Operators
Getting Loopy with Loops
Making Decisions
Defining Python Functions
Creating Classes and Objects
Handling Exceptions
Part 2: Automating Common Computer Tasks
Chapter 4: Automating Files and Folders
Demystifying the Buzzwords
Playing It Safe
Navigating Folders and Files
Organizing Files by Type
Renaming Files in Bulk
Chapter 5: Automating File Management
Deleting Old and Temporary Files
Backing Up Files
Finding and Removing Duplicate Files
Compressing Files
Decompressing Files
Chapter 6: Automating Image and Video Files
Resizing, Rotating, Flipping, and Cropping Images
Converting Image File Types
Extracting Frames from Video Files
Chapter 7: Automating Mouse and Keyboard
Granting Permissions on a Mac
Moving the Mouse, Clicking, Dragging, and Scrolling
Typing Text with Python
Detecting Keystrokes
Creating Your Own Keyboard Shortcuts
Automating Screenshots
Chapter 8: Automating the Office
Automating Microsoft Word
Automating Microsoft Excel
Creating and Opening PDFs
Watermarking PDFs
Part 3: Automating the Internet
Chapter 9: Interacting with APIs
Obtaining API Keys
Safely Storing API Keys
Handling JSON Data
Understanding REST APIs
Reviewing a Complete REST API Script
Chapter 10: Automating the Web
Automating Web Browsers
Automating Filling Forms Online
Filling Multiple Text Boxes
Filling Text Boxes from a File
Chapter 11: Scraping Web Pages
Picking the Right Tools for Web Scraping
Scraping Links from a Web Page
Extracting Data from a Web Page
Automating Data Extraction
Chapter 12: Automating Email and Text Messages
Sending Bulk Email Automatically
Automatically Sending Text Messages
Chapter 13: Automating Social Media
Acquiring API Keys and Modules
Automating Posting
Creating Content for Your Posts
Tracking Performance Metrics
Analyzing Trends
Part 4: Automating More Advanced Stuff
Chapter 14: Scheduling Tasks
Using the Schedule Module
Using the APScheduler Module
Automating Python Scripts
Chapter 15: Integrating with Artificial Intelligence
Accessing Free AI through an API
Warming Up to a Local Chatbot
Creating a Conversational Chatbot
Developing an AI Image Generator
Part 5: The Part of Tens
Chapter 16: Top Ten Zen of Python Guidelines
Beautiful Is Better than Ugly
Explicit Is Better than Implicit
Simple Is Better than Complex
Complex Is Better than Complicated
Flat Is Better than Nested
Sparse Is Better than Dense
Readability Counts
Special Cases Aren’t Special Enough to Break the Rule
Practicality Beats Purity
Errors Should Never Pass Silently
Chapter 17: Top Ten Python Error Messages
Command Not Found
No Module Named …
SyntaxError
NameError
TypeError
IndexError
KeyError
AttributeError
ModuleNotFoundError
FileNotFoundError
IndentationError
Index
About the Author
Connect with Dummies
End User License Agreement
Chapter 2
TABLE 2-1 Good and Bad Python Filenames
Chapter 3
TABLE 3-1 Formatting Directives Used with Python f-strings
TABLE 3-2 The Directives for .strftime() Formatting with datetime Values
TABLE 3-3 Arithmetic and String Concatenation Operators
TABLE 3-4 Python Assignment Operators
TABLE 3-5 Python Unary, Comparison, and other Operators
Chapter 10
TABLE 10-1 Common HTML Tags for Controls on Web Pages
Chapter 1
FIGURE 1-1: Download options from the Python website.
Chapter 2
FIGURE 2-1: Additional options for Windows.
FIGURE 2-2: The Activity Bar in VS Code. Hover the mouse pointer over any icon ...
FIGURE 2-3: Install the Python extension from Microsoft.
FIGURE 2-4: Installed Python extensions.
FIGURE 2-5: A project folder open in the Explorer pane.
FIGURE 2-6: Selecting a Python interpreter.
FIGURE 2-7: Choose the Recommended Python interpreter.
FIGURE 2-8: The Terminal in VS Code.
FIGURE 2-9: Using Python version 3.13.2 in this example.
FIGURE 2-10: A VS Code message about a newly created virtual environment.
FIGURE 2-11: The
.venv
virtual environment is active.
FIGURE 2-12: A file named
hello.py
added to the project.
FIGURE 2-13: A Python comment and some code typed into
hello.py
.
FIGURE 2-14: The Run Python File button near the upper-right corner of VS Code.
FIGURE 2-15: Result of running hello.py.
Chapter 4
FIGURE 4-1: Windows File Explorer.
FIGURE 4-2: macOS Finder.
FIGURE 4-3: The
Organize
folder for this script example.
FIGURE 4-4: The
Organize
folder after running the
Organize
script.
FIGURE 4-5: The
Practice
folder contains subfolders of files.
Chapter 5
FIGURE 5-1: A USB drive with the volume name
Backup
in the Finder.
Chapter 6
FIGURE 6-1: Images extracted from
example.mp4
are in
example_frames
.
Chapter 7
FIGURE 7-1: Allowing VS Code to control the mouse.
FIGURE 7-2: The MouseInfo app included with PyAutoGUI.
Chapter 8
FIGURE 8-1: Reducing an image’s opacity in Photopea.
Chapter 9
FIGURE 9-1: A
.env
file with an API name and key.
FIGURE 9-2: A
.gitignore
file protecting
.env
and the
.venv
folder.
FIGURE 9-3: A Python dictionary serialized into a
data.json
file.
Chapter 10
FIGURE 10-1: Allowing remote automation in Safari.
FIGURE 10-2: The Wikipedia Search box in DevTools.
Chapter 11
FIGURE 11-1: One row of data from Books to Scrape.
Chapter 12
FIGURE 12-1: A
.env
file for Python SMTP email automation.
FIGURE 12-2: A
.env
file for a hypothetical Twilio account.
Chapter 13
FIGURE 13-1: Structure of a
.env
file for posting to X.
FIGURE 13-2: Prompting ChatGPT to write social media posts.
FIGURE 13-3: The copy icon at the bottom of ChatGPT output.
FIGURE 13-4: Setting up a
.env
file for Instagram.
FIGURE 13-5: Sample output from
analyze_trends.py
.
Chapter 15
FIGURE 15-1: Store your own key in a
.env
file for this code project.
FIGURE 15-2: Ollama running in the background.
FIGURE 15-3: Checking the Ollama version from the VS Code Terminal.
FIGURE 15-4: The models I’ve downloaded.
FIGURE 15-5: AI-generated images created by
simple_images.py
.
FIGURE 15-6: AI-generated image shown in a graphical user interface.
FIGURE 15-7:
gradio
web interface for generating an image.
FIGURE 15-8: A
.env
file with an API token for Hugging Face.
FIGURE 15-9:
gradio
user interface for generating AI images.
Chapter 17
FIGURE 17-1: A virtual environment is represented by a folder in the Explorer p...
FIGURE 17-2: Make sure filenames don’t match module names.
Cover
Table of Contents
Title Page
Copyright
Begin Reading
Index
About the Author
i
ii
1
2
3
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
357
358
359
Python® Automation For Dummies®
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2026 by John Wiley & Sons, Inc. All rights reserved, including rights for text and data mining and training of artificial technologies or similar technologies.
Media and software compilation copyright © 2026 by John Wiley & Sons, Inc. All rights reserved, including rights for text and data mining and training of artificial technologies or similar technologies.
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470, or on the web at www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
The manufacturer’s authorized representative according to the EU General Product Safety Regulation is Wiley-VCH GmbH, Boschstr. 12, 69469 Weinheim, Germany, e-mail: [email protected].
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. Python is a trademark or registered trademark of Python Software Foundation in the United States. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. CERTAIN AI SYSTEMS HAVE BEEN USED IN THE CREATION OF THIS WORK. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit https://hub.wiley.com/community/support/dummies.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number is available from the publisher.
ISBN 978-1-394-37142-6 (pbk); ISBN 978-1-394-37144-0 (ebk); ISBN 978-1-394-37143-3 (ebk)
Welcome to Python Automation For Dummies, the book designed to help you find out all about Python and the many things you can do with Python to automate tedious, mundane, and time-consuming computer tasks.
You don’t need to read this book cover-to-cover to benefit. Instead, you can treat it more like a reference for building Python automation scripts and apps as needed, just by flipping to any example in the book and using the code provided in that section. Of course, I always explain the code so you understand what’s going on. That knowledge, in turn, will grow and help you come up with your own creative solutions to automation tasks and other apps.
This is not a textbook on the Python language. I don’t attempt to teach you every nook and cranny of the Python language. There are plenty of books available for that, including Python All-in-One for Dummies and Python Essentials For Dummies (published by Wiley), both of which I wrote with John Shovic.
For convenience, the kinds of tasks and code you’ll use often are summed up in Part 1 of this book. When you need a quick reminder on a fundamental task, such as starting a new app from scratch, you’ll find all the steps there. Common error messages and such are covered in Chapter 17, so you can get clarification and advice in a jiffy.
When something in Python leaves you stumped, use this book as a reference, paging through the table of contents or index to the spot that deals with that bit of information.
Within this book, you may note that some web addresses break across two lines of text. If you’re reading this book in print and want to visit one of these web pages, simply key in the web address exactly as it’s noted in the text, pretending as though the line break doesn’t exist. If you’re reading this as an e-book, you’ve got it easy — just click the web address to be taken directly to the web page.
This book doesn’t assume you’re already an accomplished software engineer with years of experience writing Python code. I do assume that you’re tech savvy enough to understand common tech jargon like files, folders, icons, copy, paste, gigabytes, and so forth.
If I assume too much, there are plenty of resources available to you to fill in the blanks. Artificial intelligence (AI) is usually your best bet for getting quick definitions and answers to tech questions. Any free AI will do. In Windows, you can use Copilot. On a Mac, you can use Apple Intelligence. Or you can use any AI that includes a free tier such as ChatGPT at https://chatgpt.com.
Throughout this book, I use icons in the margin to point out content that’s perhaps a little offbeat relative to the main flow of the text. Here’s the kind of content each icon represents:
The Tip icon alerts you to juicy information that makes computing easier — a time-saver or shortcut that’s worth keeping in mind, for example.
Don’t forget to remember these important points because you’re likely to need the information often. These are usually items that are easy to forget but well worth remembering.
When an operation could have unpleasant consequences that aren’t easily undone, the Warning icon alerts you to the dangers and tells you how to avoid that danger. Always pay attention to this icon.
I use the Technical Stuff icon when I get into the weeds on a particular subject. You can ignore anything marked with this icon without missing the main point.
In addition to the material in the print or e-book you’re reading right now, this product also comes with a free access-anywhere Cheat Sheet that covers Python data types and keywords, arithmetic and string operators, assignment operators, and more. To get this Cheat Sheet, simply go to www.dummies.com and enter Python Automation For Dummies Cheat Sheet in the Search box.
In addition, I provide all the source code for this book at www.dummies.com/go/pythonautomationfd. Finally, at that same URL you’ll find a bonus chapter called “Managing and Speeding Up the Big Jobs.”
Where you go from here is up to you! If you need a specific automation script, go to the section that describes the script you need to see all of the code for that script — not a lengthy tutorial on how to write the script. If you’re new to Python and you don’t have a lot of experience writing Python code, Chapter 1 is a great place to start.
Part 1
IN THIS PART …
Get Python onto your computer.
Download a free editor to write Python code.
Run your Python code.
Master main components of Python for automation.
Chapter 2
IN THIS CHAPTER
Choosing and installing a code editor
Creating and using virtual environments
Starting a new project
Using Python scripts
To write Python code, you need a code editor. If you’ve been coding with Python for a while and you already have a preferred editor, you’re welcome to stick with that. If you’re just starting out with Python, I recommend Visual Studio Code (VS Code for short), which is the editor I use in this book. VS Code is the most widely used code editor in the world, and it’s very well suited to Python coding.
On a personal front, I also use VS Code to write code in Cascading Style Sheets (CSS), Hypertext Markup Language (HTML), and JavaScript, the main languages for creating websites and web apps. If you’re thinking about learning that kind of coding, VS Code will serve you well there, too.
The hardware requirements for VS Code are minimal. Here’s a quick rundown:
Operating system:
Linux 64-bit distro (for example, Ubuntu 16.04+, Debian 9+, Fedora 24+, and so on); macOS 10.15 (Catalina) or later; or Windows 7, 8.1, 10, or 11 (32-bit or 64-bit).
Processor:
1.6 GHz or faster (for example, Intel Core 2 Duo, AMD Athlon 64 X2, Apple M1, or better).
Random access memory (RAM):
1GB (Linux or Windows) or 512MB (macOS). But 4GB or more is better.
Storage:
About 200MB to 300MB for the basic installation.
Display:
At least 1,024 x 768 resolution.
Most modern computers exceed those requirements considerably.
To use VS Code as your code editor, the first step is to download and install it. This is basically a matter of browsing to https://code.visualstudio.com and following the onscreen instructions. Here are step-by-step instructions — but remember, websites can change at any time, so if something is different for you, just follow any onscreen instructions you see:
Browse to
https://code.visualstudio.com
.
Click Download for Windows, Download for macOS, or Download for Linux depending on which operating system you’re using.
Open the folder to which you downloaded the file (usually your
Downloads
folder).
Double-click the icon for the downloaded file (the filename usually starts withVSCode).
If you’re using Windows, follow the onscreen instructions. When you get to the page about additional tasks, feel free to check or uncheck any boxes based on your preferences. I typically set up mine as shown in Figure 2-1.
If you’re using macOS, drag the Visual Studio Code.app file that was extracted from the downloaded Zip file to your Applications folder.
VS Code should be installed at this point. In Windows, you should be able to Start it from your Start menu (you may have to search for it on the menu if it’s not readily apparent). If you opted for a Desktop icon, double-click that icon to open VS Code. When VS Code is running, you can right-click its icon in the taskbar and choose Pin to Taskbar so you can easily start it right from the taskbar in the future.
On a Mac, you should be able to start VS Code from its icon in Launchpad or from the Applications folder. If you see a warning about VS Code being downloaded from the internet, go ahead and open it anyway. When VS Code is running, you can right-click its icon in the Dock and choose Options ⇒ Keep in Dock for easy access in the future.
FIGURE 2-1: Additional options for Windows.
VS Code offers free artificial intelligence (AI) in the form of Copilot. The first time you start VS Code, you may see the option to set up Copilot for free. It’s a great tool to help with learning to code. You’ll need a GitHub account to enable it. If you have a GitHub account, you can set up Copilot now; otherwise, you can skip that option for the time being and come back to it later.
VS Code will likely default to a dark theme, which you’re welcome to use if you prefer. However, throughout this book, I use a light theme, because the images just look better on paper that way. To choose your own theme, click Settings in VS Code (the gear icon in the lower-left corner) and choose Themes ⇒ Color Theme. I use the Light Modern theme throughout this book.
The bar of icons at the left side of VS Code (see Figure 2-2) is called the Activity Bar. It contains icons you’ll use often. To see the name of any icon, just hover the mouse pointer over the icon. In the next section, you’ll use the Extensions icon to add Python extensions to VS Code.
FIGURE 2-2: The Activity Bar in VS Code. Hover the mouse pointer over any icon to see its name.
To write Python code in VS Code, you’ll need to install the VS Code Python extensions. Follow these steps:
Click Extensions in the VS Code Activity Bar (shown near the mouse pointer in
Figure
2-2
).
In the Search box near the top of the left pane, type
Python
.
Find Python by Microsoft (it has more than 100 million downloads) and click its Install button (see Figure2-3).
Don’t worry about other Python extensions.
FIGURE 2-3: Install the Python extension from Microsoft.
It should take only a few seconds to install the extension. When it’s done, remove the search term Python from the Search box to see all your installed extensions. That list should now include Pylance, Python, and Python Debugger, as shown in Figure 2-4 (all three are included in the download).
FIGURE 2-4: Installed Python extensions.
If you hit a snag in VS Code, or you’re just wondering how to do something, feel free to ask AI for help. Virtually all modern AI chatbots can tell you anything you want to know about VS Code.
Whether you’re writing a small automation script or a large app, you’ll be working on a project. In Python, it’s always a good idea to put each project in its own folder. That folder is referred to as the workspace folder in VS Code. Before we go any further, let’s create a new empty folder so that you can see all the steps involved:
Close VS Code if it’s still open.
In Windows or Linux, choose File ⇒ Exit from the VS Code menu bar. In macOS, choose Code ⇒ Quit Visual Studio Code from the VS Code menu bar.
Navigate to wherever you’d like to put your folder.
It can be a cloud drive, if you like. Or you can just put it on the Desktop for now and move it to another location later as convenient.
Create the folder.
You should be able to just right-click an empty spot on the Desktop (or in the current folder) and choose New ⇒ Folder in Windows or New Folder in macOS.
Name the folder
First Python
(unless you prefer a different name).
If you don’t get the folder name right on the first try, right-click the folder’s icon, choose Rename, type the correct name, and press Enter.
Now that you have a new, empty folder to work with, the next step is to open that folder in VS Code.
Whether you’re starting a new project, or returning to an existing project you’ve already started, the first step will be to open the project folder in VS Code.
If you’re using Windows, you may be able to right-click the folder’s icon and choose Open With ⇒ VS Code or Show More Options ⇒ Open with Code to open VS Code and the folder simultaneously.
Regardless of what operating system you’re using, you can follow these steps to open your project folder in VS Code:
Open VS Code.
Near the top of the Activity Bar at the left, click Explorer.
Click Open Folder.
Navigate to the folder’s parent directory, click the folder’s icon, and click Open.
If you see a message about trusting the folder, choose Yes, I Trust the Authors (because you are the author!).
The Explorer pane remains open. The name of the folder you opened appears near the top of that pane (see Figure 2-5). That folder is the project’s root folder, also known as the workspace folder in VS Code. All the subfolders and files that make up your project will be contained within that workspace folder.
FIGURE 2-5: A project folder open in the Explorer pane.
Clicking the root folder name in VS Code expands and collapses it to show or hide files in that folder. Usually, you want it expanded to see subfolders and files contained within your project.
Before you start doing any actual work with Python, it’s a good idea to know what version of Python (if any) is currently active. So, the first thing you may want to do after opening a folder in VS Code is follow these steps:
From the VS Code menu bar, choose View ⇒ Command Palette.
If you prefer, press Ctrl+Shift+P in Windows or ⌘ +Shift+P in macOS. Pressing F1 may also work.
Type
sel
and click Python: Select Python Interpreter from the drop-down menu, as shown in
Figure
2-6
.
Click the Recommended Python interpreter, as shown in
Figure
2-7
, if you have multiple versions from which to choose.
You won’t see anything on the screen indicating which Python interpreter you’ve chosen, but don’t worry: I show you how to determine that, using the Terminal, in the next section.
FIGURE 2-6: Selecting a Python interpreter.
FIGURE 2-7: Choose the Recommended Python interpreter.
In this chapter, I had you select the Recommended interpreter in case you’re just getting started with Python and just want to use the latest Python version. In practice, some projects require specific Python versions, so VS Code lets you pick one each time you start it. You won’t need this for this book, but I’m mentioning it because choosing a specific version helps advanced developers.
Much of the time when working with Python, you’ll use the Terminal pane. The Terminal provides a command line interface (CLI) for entering commands from the keyboard. You can open the Terminal from the menu, or shortcut keys, as follows:
Choose View ⇒ Terminal from the menu bar.
Press F1, or press Ctrl+` in Windows or Command+` in macOS. ` is the backtick character, usually to the left of the number 1 on the keyboard.
The Terminal opens near the bottom of the VS Code window, looking something like Figure 2-8 (in Windows). The PS and path you see are the command prompt, where you type your commands.
FIGURE 2-8: The Terminal in VS Code.
In Linux and macOS, the command prompt will be different, but don’t worry about that right now. I explain more after we activate a virtual environment a little later in this chapter. However, it’s worth noting that you’re not stuck with whatever happens to be showing as your default command line shell. You can use the drop-down arrow next to the current shell name to choose a different command line shell if you like.
You always want to know what Python version you’re using in VS Code, and the Terminal lets you find out, as I explain in the next section.
To see what Python version you’re currently using, you can enter either the command python –version or python -V (the case matters here). But until you’ve set up a virtual environment (see the next section), that command may give you an error message. The trick to get around that may seem strange, but here it is:
In Windows, use
py
rather than
python
at the command.
In Linux or macOS, use
python3
rather than
python
as the command.
The reason for this weirdness has to do with the operating system PATH that determines how system commands (which are run from the operating system) have been treated in the past, and the fact that different projects may require different Python versions. Both py and python3 are aliases for the python command and will use whatever python version is currently available. In VS Code, that’s the Python version you chose when choosing Python: Select Python Interpreter from the command palette (see “Selecting your Python version,” earlier in this chapter).
Python code is case-sensitive, meaning you can’t use uppercase and lowercase letters interchangeably. You must use the same uppercase and lowercase letters shown in this book for things to work as described in this book.
When VS Code tells you it doesn’t recognize python as a command, you can still determine your Python version using the following:
In Windows, enter the command
py –version
or
py -V
to determine your Python version.
In Linux or macOS, enter the command
python3 –version
or
python3 -V
to determine your Python version.
After you type the appropriate command and press Enter, the current Python version will show just under the command you typed, as shown in Figure 2-9.
FIGURE 2-9: Using Python version 3.13.2 in this example.
After you’ve set up and activated a virtual environment, the python command will work as expected. Let’s get started on the whole business of virtual environments now.
Every Python script or app should live in its own folder (its workspace folder) for organization and portability. Each one also needs its own virtual environment, specifying the Python version and module dependencies, to run correctly. This setup lets you execute the script on any computer — Linux, macOS, Windows — regardless of the system’s Python version or installed modules.
At first, the process of creating a virtual environment may seem like a bit of a pain. But you get used to it, and the advantages are well worth the tiny effort it takes to create and activate a virtual environment.
The command to create a virtual environment is, technically, python -m venv followed by a name for the virtual environment. But, of course, that python command may fail, so you’ll have to use the py alias in Windows or the python3 alias in Linux or macOS to get it to work.
The -m is a flag the tells Python to run a module named venv as a script, rather than as a module (which is something we normally add to existing scripts rather than run directly). That name, venv is short for virtual environment.
You also need to give the virtual environment a name. The virtual environment is stored in a subfolder under the workspace folder name. You can name your virtual environment anything you like, but .venv is a common name. That .venv name offers several advantages over some name you choose at random:
The dot in
.venv
signals to other developers that the folder contains configuration or utility information and is not part of the actual Python code.
Many modern editors like VS Code and PyCharm recognize
.venv
as a virtual environment and auto-detect it for Python interpreter selection, reducing setup steps.
On Unix-like systems (Linux, macOS), files and folders starting with a dot are hidden unless the user specifically knows how to look for them. That prevents less experienced users from messing about in the
.venv
folder without knowing what they’re doing.
In short, you can think of using .venv as the virtual environment folder name a “best practice,” and the consistency will make it easier to recognize its purpose at a glance.
To create a virtual environment named .venv, open the VS Code Terminal and enter the appropriate command:
Windows:
py -m venv .venv
Linux or macOS:
python3 -m venv .venv
You won’t get any feedback in the Terminal after you press Enter. But if you look at the Explorer pane, you’ll probably see the .venv folder icon under the root of your workspace folder, First Python in our working example. You may also see the message shown in Figure 2-10 pop up in the lower-right corner of VS Code.
FIGURE 2-10: A VS Code message about a newly created virtual environment.
The message is asking if you want to associate the virtual environment with the workspace folder, which is just another name for the root folder, or the folder that contains the entire project (including the virtual environment). Go ahead and click Yes. But if you don’t get that opportunity, don’t worry about it. Activating the virtual environment each time you open the project’s folder will ensure that VS Code “knows” to use the Python version and add-ins from the virtual environment every time you open that folder to run or work on your script.
Creating a virtual environment doesn’t activate the virtual environment. You always want to make sure your virtual environment is activated before you start working on your script or run a script. That you’ll do in the Terminal window of VS Code. The command prompt in the Terminal should still show the path of the workspace root folder. Enter one of the commands to run the activate script within that folder, depending on your operating system:
Windows:
.venv\Scripts\activate
Linux or macOS:
.venv/bin/activate
Notice that Windows uses backslashes (\), while Linux and macOS use forward slashes (/). Remember to use the same uppercase/lowercase letters shown here.
If you see a warning about the script coming from an “unknown publisher,” type A and press Enter to always run. The publisher in this instance is the Python Software Foundation, which created the venv module, and you can certainly trust them.
When a virtual environment is active, the name of that virtual environment shows in the command prompt, so you know the virtual environment. Figure 2-11 shows how the command prompt may look in Windows, where the name .venv is enclosed in parentheses at the start of the command prompt.
In a Linux or macOS environment, the command prompt path won’t look the same as shown in Figure 2-11. If you’re using the zsh command line shell, then it will look more like this:
.venvalan@MacBookAir First Python %
FIGURE 2-11: The .venv virtual environment is active.
If you’re using the bash shell, it will look more like this:
.venvMacBookAir:First Python alan$
On your own computer, MacBookAir will be the name of the computer you’re using, and alan will be your own username.
Z shell (or zsh) is a command-line interpreter shell, similar to Bash (short for Bourne Again Shell), but with more capabilities. Until macOS Catalina 10.15, released in 2019, macOS used Bash as the default shell; since then, zsh has been the default shell for macOS.
You can choose which command line shell you want to use by clicking the drop-down arrow next to the current shell name near the upper-right corner of the Terminal (refer to Figure 2-8). But Python commands should work the same way with either shell.
After you’ve activated a virtual environment, you no longer need to use an alias like py or python3 instead of python in a command. The python command works without the alias. So, now you can use python --version or python -V to see the version number of Python you’re using for the current project.
