### Create Example File and Folder with pathlib Source: https://automatetheboringstuff.com/3e/chapter11.html This snippet demonstrates how to create a sample directory and a text file within it using Python's pathlib module. This setup is useful for practicing file operations with the shutil module. It ensures the directory is created if it doesn't exist and writes 'Hello' to the file. ```python from pathlib import Path h = Path.home() (h / 'spam').mkdir(exist_ok=True) with open(h / 'spam/file1.txt', 'w', encoding='utf-8') as file: file.write('Hello') ``` -------------------------------- ### Running IDLE on Ubuntu Source: https://automatetheboringstuff.com/3e/chapter0.html This command starts the IDLE integrated development environment on Ubuntu Linux. IDLE is typically installed alongside the Python interpreter. If the command is not found, ensure Python 3 and IDLE are properly installed. ```bash idle ``` -------------------------------- ### Python Clipboard Recorder: Initialization and Loop Structure Source: https://automatetheboringstuff.com/3e/chapter12.html This snippet shows the initial setup of the Python clipboard recorder. It imports necessary modules ('pyperclip', 'time'), displays a starting message, and initializes a variable to track previous clipboard content. The core logic resides within a try-except block to handle user interruption. ```python import pyperclip, time print('Recording clipboard... (Ctrl-C to stop)') previous_content = '' ``` -------------------------------- ### Install 'automateboringstuff3' Package Source: https://automatetheboringstuff.com/3e/chapter12.html Installs the 'automateboringstuff3' package, which serves as a container for specific versions of packages used in the 'Automate the Boring Stuff' book. This command is run from an activated virtual environment in the terminal. ```bash # On Windows python –m pip install automateboringstuff3 ``` ```bash # On macOS and Linux python3 –m pip install automateboringstuff3 ``` -------------------------------- ### Install Python Package using pip Source: https://automatetheboringstuff.com/3e/chapter12.html Installs a specified package from the Python Package Index (PyPI). This command is run from the terminal and requires the 'python -m pip install' command followed by the package name. On macOS and Linux, 'python3' should be used instead of 'python'. ```bash C:\Users\al>\n**python –m pip install ****package_name** ``` ```bash # On macOS and Linux, use python3 instead of python python3 –m pip install ****package_name** ``` -------------------------------- ### Handling Dates and Times in Python Source: https://automatetheboringstuff.com/3e/appendixb.html Provides examples of common date and time operations in Python. It includes getting the current time, formatting time into a readable string, pausing execution, and working with datetime and timedelta objects. It also demonstrates how to find the day of the week. ```python import time import datetime # Get current time current_time = time.time() print(f'Current time (seconds since epoch): {current_time}') # Format time as a readable string asctime_time = time.asctime() print(f'Current time (asctime): {asctime_time}') # Pause execution time.sleep(5) print('Slept for 5 seconds.') # Create a datetime object date_obj = datetime.datetime(2019, 1, 7) print(f'Datetime object: {date_obj}') # Create a timedelta object timedelta_obj = datetime.timedelta(days=7) print(f'Timedelta object: {timedelta_obj}') # Get the day of the week (Monday is 0) day_of_week = date_obj.weekday() print(f'Day of the week for {date_obj}: {day_of_week}') ``` -------------------------------- ### Install Whisper Speech Recognition Package Source: https://automatetheboringstuff.com/3e/chapter24.html Installs the Whisper speech recognition system using pip. Note that the package name is 'openai-whisper', not 'whisper'. This is a large download and may take time. ```bash pip install openai-whisper ``` -------------------------------- ### TSV Data Export Example Source: https://automatetheboringstuff.com/3e/chapter24.html An example of TSV (Tab-Separated Values) data exported from Whisper, useful for further processing in other programs. It includes start time, end time, and text. ```plaintext start end text 0 5640 Dinosaurs are a diverse group of reptiles of the clade dinosauria. They 5640 14960 appeared during the triassic period. Between 245 and 233.23 million years ago. --snip-- ``` -------------------------------- ### Generate and Speak Text with pyttsx3 Source: https://automatetheboringstuff.com/3e/chapter24.html Initializes the text-to-speech engine, speaks a greeting, takes user input, and responds verbally. Requires the pyttsx3 library. ```python import pyttsx3 engine = pyttsx3.init() engine.say('Hello. How are you doing?') engine.runAndWait() # The computer speaks. feeling = input('>') engine.say('Yes. I am feeling ' + feeling + ' as well.') engine.runAndWait() # The computer speaks again. ``` -------------------------------- ### Get Installed Tesseract Languages with PyTesseract Source: https://automatetheboringstuff.com/3e/chapter22.html This Python code snippet demonstrates how to retrieve a list of all installed language packs for Tesseract using the pytesseract library. This is useful for verifying language pack installations before attempting to process images in different languages. ```python import pytesseract as tess print(tess.get_languages()) ``` -------------------------------- ### Create and Manage Meal Ingredients Database (SQL and Python) Source: https://automatetheboringstuff.com/3e/chapter16.html This project involves creating two SQL tables, 'meals' and 'ingredients', and then using Python to manage them. The program allows users to add meals with ingredients, query for a meal's ingredients, or find meals containing a specific ingredient. It handles user input for adding data and exiting the program. ```sql CREATE TABLE IF NOT EXISTS meals (name TEXT) STRICT CREATE TABLE IF NOT EXISTS ingredients (name TEXT, meal_id INTEGER, FOREIGN KEY(meal_id) REFERENCES meals (rowid)) STRICT ``` ```python import sqlite3 import sys def setup_database(db_path='meals.db'): conn = sqlite3.connect(db_path) cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS meals ( name TEXT UNIQUE ) STRICT """) cursor.execute(""" CREATE TABLE IF NOT EXISTS ingredients ( name TEXT, meal_id INTEGER, FOREIGN KEY(meal_id) REFERENCES meals(rowid) ) STRICT """) conn.commit() return conn def add_meal(conn, meal_name, ingredients): cursor = conn.cursor() try: cursor.execute("INSERT INTO meals (name) VALUES (?)", (meal_name,)) meal_id = cursor.lastrowid for ingredient in ingredients: cursor.execute("INSERT INTO ingredients (name, meal_id) VALUES (?, ?)", (ingredient.strip(), meal_id)) conn.commit() print(f"Meal added: {meal_name}") except sqlite3.IntegrityError: print(f"Meal '{meal_name}' already exists.") except Exception as e: print(f"Error adding meal: {e}") def get_meal_ingredients(conn, meal_name): cursor = conn.cursor() cursor.execute("SELECT rowid FROM meals WHERE name = ?", (meal_name,)) meal_row = cursor.fetchone() if meal_row: meal_id = meal_row[0] cursor.execute("SELECT name FROM ingredients WHERE meal_id = ?", (meal_id,)) ingredients = cursor.fetchall() print(f"Ingredients of {meal_name}:") for ingredient in ingredients: print(f" {ingredient[0]}") else: print(f"Meal '{meal_name}' not found.") def get_meals_by_ingredient(conn, ingredient_name): cursor = conn.cursor() cursor.execute(""" SELECT DISTINCT m.name FROM meals m JOIN ingredients i ON m.rowid = i.meal_id WHERE i.name = ? """) meals = cursor.fetchall() if meals: print(f"Meals that use {ingredient_name}:") for meal in meals: print(f" {meal[0]}") else: print(f"Ingredient '{ingredient_name}' not found in any meals.") def main(): conn = setup_database() print("Enter meal and ingredients (e.g., 'meal:ingredient1,ingredient2'), a meal name, an ingredient name, or 'quit' to exit.") while True: user_input = input("> ").strip() if user_input.lower() == 'quit': break if ':' in user_input: try: meal_part, ingredients_part = user_input.split(':', 1) meal_name = meal_part.strip() ingredients = [ing.strip() for ing in ingredients_part.split(',')] add_meal(conn, meal_name, ingredients) except ValueError: print("Invalid format. Use 'meal:ingredient1,ingredient2'.") else: # Check if it's a meal or an ingredient cursor = conn.cursor() cursor.execute("SELECT name FROM meals WHERE name = ?", (user_input,)) if cursor.fetchone(): get_meal_ingredients(conn, user_input) else: cursor.execute("SELECT name FROM ingredients WHERE name = ?", (user_input,)) if cursor.fetchone(): get_meals_by_ingredient(conn, user_input) else: print(f"'{user_input}' not found as a meal or ingredient.") conn.close() # Example usage: # main() ``` -------------------------------- ### Get Screen Resolution and Mouse Position Source: https://automatetheboringstuff.com/3e/chapter23.html Retrieve information about the screen's dimensions and the current position of the mouse cursor. This is useful for dynamic positioning and validation. Requires PyAutoGUI installation (`pip install pyautogui`). ```python import pyautogui # Get screen resolution (width, height)screenWidth, screenHeight = pyautogui.size() print(f"Screen resolution: {screenWidth}x{screenHeight}") # Get current mouse coordinatescurrentMouseX, currentMouseY = pyautogui.position() print(f"Current mouse position: ({currentMouseX}, {currentMouseY})") ``` -------------------------------- ### Initialize Quiz and Answer Key Files in Python Source: https://automatetheboringstuff.com/3e/chapter10.html This code snippet demonstrates how to open and prepare quiz and answer key files for writing. It uses f-strings to create unique filenames based on a loop counter and specifies UTF-8 encoding for broad character support. The 'w' mode ensures that new files are created or existing ones are overwritten. ```python quiz_file = open(f'capitalsquiz{quiz_num + 1}.txt', 'w', encoding='UTF-8') answer_file = open(f'capitalsquiz_answers{quiz_num + 1}.txt', 'w', encoding='UTF-8') ``` -------------------------------- ### Python Code Blocks and Indentation Example Source: https://automatetheboringstuff.com/3e/chapter2.html Illustrates how Python uses indentation to define blocks of code. This example shows nested blocks within an if-else structure, highlighting how indentation increases to start a new block and decreases to end it. ```python username = 'Mary' password = 'swordfish' if username == 'Mary': print('Hello, Mary') if password == 'swordfish': print('Access granted.') else: print('Wrong password.') ``` -------------------------------- ### Interact with SQLite Database via Command Line Source: https://automatetheboringstuff.com/3e/chapter16.html This snippet demonstrates how to connect to a SQLite database file using the sqlite3 command-line tool. It shows how to create a table, insert data, and select records. SQL queries must end with a semicolon. The .help command provides usage hints. ```bash C:\Users\Al>\sqlite3 example.db SQLite version 3.xx.xx Enter ".help" for usage hints. sqlite> CREATE TABLE IF NOT EXISTS cats (name TEXT NOT NULL, birthdate TEXT, fur TEXT, weight_kg REAL) STRICT; sqlite> INSERT INTO cats VALUES ('Zophie', '2021-01-24', 'gray tabby', 4.7); sqlite> SELECT * from cats; Zophie|2021-01-24|gray tabby|4.7 sqlite> .tables cats sqlite> .headers on sqlite> SELECT * from cats; name|birthdate|fur|weight_kg Zophie|2021-01-24|gray tabby|4.7 ``` -------------------------------- ### Python String Indexing and Slicing Examples Source: https://automatetheboringstuff.com/3e/chapter8.html Demonstrates how to access individual characters and substrings within a Python string using indexing and slicing. Indexing starts at 0, and slicing allows for extracting portions of the string. ```python print('Hello, world!'[1]) # Output: e print('Hello, world!'[0:5]) # Output: Hello print('Hello, world!'[:5]) # Output: Hello print('Hello, world!'[3:]) # Output: lo, world! ``` -------------------------------- ### Python: First Program - Hello World and User Input Source: https://automatetheboringstuff.com/3e/chapter1.html This Python program prints a greeting, asks for the user's name and age, and then prints a personalized message and calculates the user's age next year. It demonstrates basic print statements, input() function for user interaction, string concatenation, and integer conversion with arithmetic. ```python # This program says hello and asks for my name. print('Hello, world!') print('What is your name?') # Ask for their name. my_name = input('>') print('It is good to meet you, ' + my_name) print('The length of your name is:') print(len(my_name)) print('What is your age?') # Ask for their age. my_age = input('>') print('You will be ' + str(int(my_age) + 1) + ' in a year.') ``` -------------------------------- ### Get Element Text and HTML using Playwright Source: https://automatetheboringstuff.com/3e/chapter13.html Demonstrates how to retrieve the inner text and inner HTML of the first paragraph element on a page using Playwright's locator and nth() methods. Requires Playwright to be installed. ```python from playwright.sync_api import sync_playwright with sync_playwright() as playwright: browser = playwright.firefox.launch(headless=False, slow_mo=50) page = browser.new_page() page.goto('https://autbor.com/example3.html') elems = page.locator('p') print(elems.nth(0).inner_text()) print(elems.nth(0).inner_html()) ``` -------------------------------- ### Get Mouse Cursor Position with PyAutoGUI Source: https://automatetheboringstuff.com/3e/appendixb.html The pyautogui.position() function returns a tuple with the current x and y coordinates of the mouse cursor on the screen. This can be used to track the mouse or set starting points for movements. ```python import pyautogui x, y = pyautogui.position() print(f"Mouse position: X={x}, Y={y}") ``` -------------------------------- ### Write and Read Text File using pathlib Source: https://automatetheboringstuff.com/3e/chapter10.html Demonstrates how to write content to a text file and then read it back using the pathlib module. This method is concise for simple text file operations. It requires the pathlib module to be imported. ```python from pathlib import Path p = Path('spam.txt') p.write_text('Hello, world!') print(p.read_text()) ``` -------------------------------- ### Filter Data Using LIKE for Pattern Matching in SQLite Source: https://automatetheboringstuff.com/3e/chapter16.html This snippet illustrates how to use the `LIKE` operator in SQLite for pattern matching. It retrieves rows where a column's value matches a pattern, using the percent sign (%) as a wildcard. Examples include matching names ending with 'y' and starting with 'Ja'. ```python import sqlite3 conn = sqlite3.connect('sweigartcats.db', isolation_level=None) conn.execute('SELECT rowid, name FROM cats WHERE name LIKE "%y"').fetchall() conn.execute('SELECT rowid, name FROM cats WHERE name LIKE "Ja%"').fetchall() ``` -------------------------------- ### Change Directory (cd) Command Examples Source: https://automatetheboringstuff.com/3e/chapter12.html Demonstrates changing the current working directory using the 'cd' command on Windows and macOS/Linux. This includes navigating to specific folders, moving up one directory, and changing to absolute paths. ```shell C:\Users\al> **cd Desktop** C:\Users\al\Desktop> **cd ..** C:\Users\al> **cd C:\Windows\System32** C:\Windows\System32> ``` ```shell D:\> **cd backup** D:\backup> ``` -------------------------------- ### Create Ubuntu Linux Desktop Entry Source: https://automatetheboringstuff.com/3e/chapter12.html This snippet shows the content for a `.desktop` file on Ubuntu Linux, which creates an application entry in the system's application menu for the clipboard recorder. It specifies the name and the command to execute, launching the script within a terminal window. ```ini [Desktop Entry] Name=Clipboard Recorder Exec=gnome-terminal -- /home/al/cliprec Type=Application ``` -------------------------------- ### Clipboard Input/Output with Pyperclip in Python Source: https://automatetheboringstuff.com/3e/chapter12.html The pyperclip module allows Python programs to interact with the system clipboard. Use pyperclip.paste() to get text from the clipboard and pyperclip.copy() to place text onto the clipboard. Pyperclip needs to be installed via pip and may require additional system packages on Linux. ```python import pyperclip # Get text from clipboard clipboard_text = pyperclip.paste() print(f"Text from clipboard: {clipboard_text}") # Copy text to clipboard new_text = "This text will be copied to the clipboard." pyperclip.copy(new_text) print(f"Copied to clipboard: {new_text}") ``` -------------------------------- ### Understanding Page Range for PyPDF append() Source: https://automatetheboringstuff.com/3e/chapter17.html These examples illustrate how the range tuple (start, stop, [step]) passed to PyPDF's PdfWriter.append() method determines which pages are copied. It shows the direct mapping between the tuple arguments and the output of Python's range() function. ```python list(range(0, 5)) # Passing (0, 5) makes append() copy these pages: [0, 1, 2, 3, 4] list(range(0, 5, 2)) # Passing (0, 5, 2) makes append() copy these pages: [0, 2, 4] ``` -------------------------------- ### Create and Backup In-Memory SQLite Database to File Source: https://automatetheboringstuff.com/3e/chapter16.html This snippet demonstrates creating an in-memory SQLite database, inserting data, and then backing it up to a file named 'test.db'. It uses the sqlite3 module and the backup() method. ```python import sqlite3 # Create an in-memory database. memory_db_conn = sqlite3.connect(':memory:', isolation_level=None) memory_db_conn.execute('CREATE TABLE test (name TEXT, number REAL)') memory_db_conn.execute('INSERT INTO test VALUES ("foo", 3.14)') # Connect to a file-based database. file_db_conn = sqlite3.connect('test.db', isolation_level=None) # Save the in-memory database to the file. memory_db_conn.backup(file_db_conn) ``` -------------------------------- ### Send Key Press Strings with PyAutoGUI (Python) Source: https://automatetheboringstuff.com/3e/chapter23.html Demonstrates how to send virtual key presses to the computer using PyAutoGUI's write() function. This example types 'Hello, world!' into an active window after clicking a specific coordinate. ```python import pyautogui # Clicks at coordinates (100, 200) and then types 'Hello, world!' pyautogui.click(100, 200); pyautogui.write('Hello, world!') # Types 'Hello, world!' with a 0.25-second pause between each character pyautogui.write('Hello, world!', 0.25) ``` -------------------------------- ### Create SQLite Indexes using Python Source: https://automatetheboringstuff.com/3e/chapter16.html Demonstrates how to connect to a SQLite database and create indexes on specified columns ('name' and 'birthdate') in the 'cats' table using Python. This speeds up queries that filter by these columns. ```python import sqlite3 conn = sqlite3.connect('sweigartcats.db', isolation_level=None) conn.execute('CREATE INDEX idx_name ON cats (name)') conn.execute('CREATE INDEX idx_birthdate ON cats (birthdate)') ``` -------------------------------- ### Launch qBittorrent with a Torrent File (Python) Source: https://automatetheboringstuff.com/3e/chapter20.html This Python code snippet demonstrates how to launch the qBittorrent application with a specific torrent file using the subprocess.Popen() function. Ensure the path to qbittorrent.exe is correct for your system. ```python import subprocess qbProcess = subprocess.Popen(['C:\\Program Files (x86)\\qBittorrent\\qbittorrent.exe', 'shakespeare_complete_works.torrent']) ``` -------------------------------- ### Accessing Columns as Lists in Openpyxl Source: https://automatetheboringstuff.com/3e/chapter14.html This code illustrates how to access all cells within a specific column of an openpyxl Worksheet. It involves loading a workbook, selecting a sheet, and then converting the sheet's columns attribute to a list. Individual columns can then be accessed by their index. The example shows how to get the second column (index 1) and print the value of each cell in that column. ```python import openpyxl wb = openpyxl.load_workbook('example3.xlsx') sheet = wb['Sheet1'] # Get the second column's cells (index 1). second_column_cells = list(sheet.columns)[1] for cell_obj in second_column_cells: print(cell_obj.value) ``` -------------------------------- ### Python Interactive Shell: Basic Arithmetic and Evaluation Source: https://automatetheboringstuff.com/3e/chapter1.html Demonstrates basic arithmetic operations and how Python evaluates expressions in the interactive shell. Shows simple addition and single values as expressions. ```python >>> 2 + 2 4 >>> 2 2 ``` -------------------------------- ### Create Python Virtual Environment Source: https://automatetheboringstuff.com/3e/chapter12.html This command creates a new virtual environment for a Python project. It uses the built-in `venv` module to create an isolated Python installation in a specified directory (conventionally named `.venv`). This ensures that packages installed within this environment do not interfere with the global Python installation or other projects. ```bash python -m venv .venv ``` -------------------------------- ### Desktop Entry for Application Launch Source: https://automatetheboringstuff.com/3e/chapter12.html This .desktop file configuration allows an application to be launched from a desktop environment's application menu (like Ubuntu's Dash). It specifies the application name and the command to execute, often using a terminal emulator. ```ini [Desktop Entry] Name=yourScript Exec=gnome-terminal -- /home/al/Scripts/yourScript Type=Application ``` -------------------------------- ### List Installed Python Packages with pip Source: https://automatetheboringstuff.com/3e/chapter12.html Lists all installed Python packages and their versions. This command is executed in the terminal. On macOS and Linux, 'python3' should be used instead of 'python'. ```bash C:\Users\al>\n**python -m pip list** ``` ```bash # On macOS and Linux, use python3 instead of python python3 -m pip list ``` -------------------------------- ### SQLite: Connect and Create Table Source: https://automatetheboringstuff.com/3e/appendixb.html Demonstrates how to establish a connection to an SQLite database file and create a new table with specified columns and data types using Python's `sqlite3` module. It uses `isolation_level=None` for autocommit. ```python import sqlite3 # Connect to an SQLite database (creates the file if it doesn't exist) # isolation_level=None enables autocommit mode conn = sqlite3.connect('example.db', isolation_level=None) # Create a table with STRICT mode (enforces data types) conn.execute(''' CREATE TABLE students ( first_name TEXT, last_name TEXT, favorite_color TEXT ) STRICT ''') print("Table 'students' created successfully.") # Close the connection conn.close() ``` -------------------------------- ### SRT Subtitle File Example Source: https://automatetheboringstuff.com/3e/chapter24.html An example of the first part of an SRT (SubRip Subtitle) file, commonly used for video subtitles. It includes sequence numbers and timecodes. ```plaintext 1 00:00:00,000 --> 00:00:05,640 Dinosaurs are a diverse group of reptiles of the clade dinosauria. They first 2 00:00:05,640 --> 00:00:14,960 appeared during the triassic period. Between 245 and 233.23 million years ago. --snip-- ``` -------------------------------- ### Load SQLite Database File into In-Memory Database Source: https://automatetheboringstuff.com/3e/chapter16.html This example shows how to load an existing SQLite database file ('sweigartcats.db') into an in-memory database using the backup() method. It then queries the in-memory database to display the first three entries from the 'cats' table. ```python import sqlite3 # Connect to the file-based database. file_db_conn = sqlite3.connect('sweigartcats.db', isolation_level=None) # Create an in-memory database. memory_db_conn = sqlite3.connect(':memory:', isolation_level=None) # Load the file database into memory. file_db_conn.backup(memory_db_conn) # Query the in-memory database. print(memory_db_conn.execute('SELECT * FROM cats LIMIT 3').fetchall()) ``` -------------------------------- ### Match String Start with Regex in Python Source: https://automatetheboringstuff.com/3e/chapter9.html Uses the caret symbol '^' to ensure a regex pattern matches only at the beginning of a string. Demonstrates searching for strings starting with 'Hello'. ```python import re begins_with_hello = re.compile(r'^Hello') print(begins_with_hello.search('Hello, world!')) print(begins_with_hello.search('He said "Hello."') == None) ``` -------------------------------- ### Install Specific Version of Python Package using pip Source: https://automatetheboringstuff.com/3e/chapter12.html Installs a specific version of a package from PyPI. This command is run from the terminal. On macOS and Linux, 'python3' should be used instead of 'python'. ```bash python –m pip install package_name==1.17.4 ``` ```bash # On macOS and Linux, use python3 instead of python python3 –m pip install package_name==1.17.4 ``` -------------------------------- ### Control Window States (Maximize, Minimize, Activate, Restore, Close) (Python) Source: https://automatetheboringstuff.com/3e/chapter23.html Shows how to check and change the maximized, minimized, and active states of a window using PyAutoGUI. It includes methods to maximize, restore, minimize, activate, and close windows. ```python import pyautogui import time active_win = pyautogui.getActiveWindow() # Returns True if the window is maximized print(active_win.isMaximized) # Returns True if the window is minimized print(active_win.isMinimized) # Returns True if the window is the active window print(active_win.isActive) # Maximizes the window active_win.maximize() print(active_win.isMaximized) # Undoes a minimize/maximize action active_win.restore() # Minimizes the window active_win.minimize() # Waits 5 seconds while you activate a different window: time.sleep(5) active_win.activate() # This will close the window you're typing in. active_win.close() ``` -------------------------------- ### Launch MouseInfo Application with PyAutoGUI Source: https://automatetheboringstuff.com/3e/chapter23.html This code snippet demonstrates how to import the pyautogui library and launch the MouseInfo application. MouseInfo helps in identifying screen coordinates and pixel colors, which is crucial for automating mouse clicks. It is intended to be run from an interactive shell. ```python import pyautogui pyautogui.mouseInfo() ``` -------------------------------- ### VTT Subtitle File Example Source: https://automatetheboringstuff.com/3e/chapter24.html An example of the first part of a VTT (Web Video Text Tracks) file, a modern standard for video subtitles. It includes timecodes and text content. ```plaintext WEBVTT 00:00.000 --> 00:05.640 Dinosaurs are a diverse group of reptiles of the clade dinosauria. They first 00:05.640 --> 00:14.960 appeared during the triassic period. Between 245 and 233.23 million years ago. --snip-- ``` -------------------------------- ### Simulate Keyboard Input with PyAutoGUI Source: https://automatetheboringstuff.com/3e/chapter23.html Send keystrokes and keyboard shortcuts to applications. This allows for typing text and triggering actions like copy-paste. PyAutoGUI needs to be installed (`pip install pyautogui`). ```python import pyautogui # Type the string "Hello, world!" pyautogui.write('Hello, world!') # Type with a slight pause between characters pyautogui.write('Slower typing', interval=0.25) # Press special keys like the Enter key pyautogui.press('enter') # Press the left arrow key pyautogui.press('left') # Simulate hotkeys like Ctrl+C (copy) pyautogui.hotkey('ctrl', 'c') # Simulate hotkeys like Ctrl+A (select all) pyautogui.hotkey('ctrl', 'a') ``` -------------------------------- ### Execute Programs from Terminal Source: https://automatetheboringstuff.com/3e/chapter12.html Illustrates how to run executable programs from the terminal. This includes specifying the program name directly, using './' on macOS/Linux, and providing the full absolute path. ```shell On Windows, enter the program name with or without the _.exe_ extension: example.exe. On macOS and Linux, enter ./ followed by the program name: ./example. ``` ```shell Full absolute path: C:\full\path\to\example.exe or /full/path/to/example. ``` -------------------------------- ### Python Interactive Shell: Order of Operations and Parentheses Source: https://automatetheboringstuff.com/3e/chapter1.html Illustrates Python's order of operations (precedence) for arithmetic operators and how parentheses can be used to override this order. Includes examples of multiplication, exponentiation, division, integer division, and modulus. ```python >>> 2 + 3 * 6 20 >>> (2 + 3) * 6 30 >>> 48565878 * 578453 28093077826734 >>> 2 ** 8 256 >>> 23 / 7 3.2857142857142856 >>> 23 // 7 3 >>> 23 % 7 2 >>> 2 + 2 4 >>> (5 - 1) * ((7 + 1) / (3 - 1)) 16.0 ``` -------------------------------- ### Take Screenshot with PyAutoGUI Source: https://automatetheboringstuff.com/3e/chapter23.html Capture the current screen content and save it to an image file. This can be used for logging, debugging, or as input for image recognition tasks. Requires PyAutoGUI installation (`pip install pyautogui`). ```python import pyautogui # Take a screenshot of the entire screen and save itscreenshot = pyautogui.screenshot('screenshot.png') print("Screenshot saved as screenshot.png") # You can also get an image object without saving directly img = pyautogui.screenshot() # Process the image object as needed ``` -------------------------------- ### Save Speech to WAV File with pyttsx3 Source: https://automatetheboringstuff.com/3e/chapter24.html Initializes the text-to-speech engine and saves generated speech to a WAV file. Requires the pyttsx3 library. Note: Only WAV format is supported. ```python import pyttsx3 engine = pyttsx3.init() engine.save_to_file('Hello. How are you doing?', 'hello.wav') engine.runAndWait() # The computer creates hello.wav. ```