☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 3 : Processing : Case Studies : Automation

Automation

Overview

Automation programming is a discipline within software development that involves creating programs or scripts to automate repetitive tasks or processes. It aims to streamline workflows, increase efficiency, and reduce human error by replacing manual interventions with automated solutions. Automation programming is widely used across various industries and domains, ranging from system administration and software testing to data analysis and web scraping.

Python offers a wide range of tools and libraries that make automation programming efficient and straightforward. Here are some examples of how Python can be used for automation:

Thinking in Terms of Automation

Thinking in terms of automation refers to adopting a mindset that seeks to identify opportunities for automating tasks, processes, and workflows to increase efficiency, productivity, and accuracy. It involves analyzing repetitive or time-consuming activities and considering how they can be streamlined or eliminated through the use of automated solutions. By embracing this mindset, individuals and organizations can optimize their operations and focus on more valuable and strategic work.

Automation programming differs from user-centric software. A fully automated application has little to no output, so the traditional model of input-processing-output becomes input-processing. In this context then, the automation programmer has to eliminate all output, including error messages, because the application is intended to operate without human interaction. So, there is no one sitting in front of a computer screen to see the error messages or any other output. If you consider the enormous number of possible situations and errors that can occur in software, seemingly simple tasks require a great deal of forethought and planning.

To think in terms of automation, there are several key aspects to consider:

By adopting a mindset of thinking in terms of automation, individuals and organizations can unlock significant benefits. Automation frees up time and resources, reduces errors, improves efficiency, and enables a focus on higher-value tasks. It empowers individuals to leverage technology to its fullest potential and embrace the transformative power of automation in a rapidly evolving world.

Persistent Automation Processes

Persistent automation processes in Python refer to long-running tasks or workflows that are designed to run continuously or repeatedly, typically in the background, without the need for manual intervention. These processes automate repetitive tasks, handle data processing, or perform other operations that require continuous execution.

Here is a detailed description of persistent automation processes in Python:

Also, to ensure that a persistent automation process survives computer reboots, shutdowns, and restarts, you need to employ techniques for persistence and process management. Here's an explanation of how to achieve this:

By combining these techniques, you can create a robust and persistent automation process in Python that survives computer reboots, shutdowns, and restarts. It ensures that the process resumes execution from its last state, handles errors gracefully, and recovers from failures to maintain continuity and reliability in automation workflows.

Scheduling Tasks in Python

There are numerous approaches to scheduling tasks in Python. A popular approach is using the schedule library (You can read more about this library and find full documentation on Pypi.org here  or the schedule library home page here ). This library provides an intuitive approach for scheduling tasks in Python code. It can handle scheduling at a variety of intervals using its every() method, for example, every # minutes, hour, day, day of the week, every specified second of every minute, etc.

Schedule Library General Form

import schedule
schedule.every().[interval].at([time]).do([job])

Note: The general form presented here is simplified for our purposes here. See the full documentation ) for all of the options.

Code Details

Examples

schedule.every(10).seconds.do(job)
schedule.every(10).minutes.do(job)
schedule.every(10).hours.do(job)
schedule.every(10).days.do(job)
schedule.every(10).weeks.do(job)
schedule.every().monday.at("09:00").do(job)
schedule.every().friday.at("23:59").do(job)

Note: In the above examples, job represents any callable function or code that would contain the logic you want to run when the schedule event is activated.

Code Details

Implementation Examples

Logging Disk Space on an Schedule

In this example, we'll write a simple Python program that checks the amount of disk space a particular directory is consuming and write that information to a log file. This information could be used by a System Adminstrator to see the growth pattern of a directory over time. For demonstration purposes, the following code example checks a folder every thirty seconds, which would be very frequent for a real application. But using this example, I was able to demonstrate activity in a folder by moving files in and out of the folder over a short period of time. In a real implementation, the time schedule would likely be set to a wider timespan.

Code

import os
import datetime
import schedule
import time

TEMP_FOLDER = "c:\\TempFolder\\"
LOG_FILE = 'TempFolderDiskSpace.log'

def get_folder_size():
    total_size = 0
    for path, _, files in os.walk(TEMP_FOLDER):
        for file in files:
            file_path = os.path.join(path, file)
            total_size += os.path.getsize(file_path)
    return total_size

def write_to_log_file(size):
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"{timestamp} - Size: {size} bytes\n"
    with open(LOG_FILE, 'a') as file:
        file.write(log_entry)

def check_folder_size():
    folder_size = get_folder_size()
    write_to_log_file(folder_size)

schedule.every(10).seconds.do(check_folder_size)

while True:
    schedule.run_pending()
    time.sleep(1)

Log File Output Example

The code above builds a log file containing one entry for each run of the automation. Each entry indicates the time and cumulative size of all of the files in the directory being monitored, as shown below.

2023-02-20 21:40:21 - Size: 0 bytes
2023-02-20 21:40:52 - Size: 8845308 bytes
2023-02-20 21:41:22 - Size: 8845308 bytes
2023-02-20 21:41:52 - Size: 8845308 bytes
2023-02-20 21:42:22 - Size: 32913212 bytes
2023-02-20 21:42:52 - Size: 455509692 bytes
2023-02-20 21:43:23 - Size: 2007772428 bytes
2023-02-20 21:43:53 - Size: 2861877172 bytes
2023-02-20 21:44:23 - Size: 2861877172 bytes
2023-02-20 21:44:53 - Size: 2861877172 bytes
2023-02-20 21:45:24 - Size: 1946145612 bytes
2023-02-20 21:45:54 - Size: 1433494891 bytes
2023-02-20 21:46:24 - Size: 8845308 bytes
2023-02-20 21:46:54 - Size: 1739204948 bytes
2023-02-20 21:47:24 - Size: 823473388 bytes
2023-02-20 21:47:55 - Size: 2591 bytes
2023-02-20 21:48:25 - Size: 0 bytes
2023-02-20 21:48:55 - Size: 0 bytes

As we can see by the contents of the log file, the first iteration indicated that the directory was empty (Line 1). then files were added to the folder (Lines 2 thru 10), removed from the folder (Lines 11 thru 13), and more added (Line 14). Ultimately all files were removed and it returned to empty (Lines 17 thru 18).

Code Details

Purging Temp Files on an Schedule

In this example, we'll write a simple Python program that purges (deletes) the contents of a temp folder (directory) on a scheduled basis.

Code

import os
import datetime
import schedule
import time

TEMP_FOLDER = "c:\\TempFolder\\"    # This can be any folder where temp files are stored
LOG_FILE = 'TempFolderPurge.log'
DAYS_OLD = 7  # Age in days after which files will be purged

def get_folder_size():
    total_size = 0
    for path, _, files in os.walk(TEMP_FOLDER):
        for file in files:
            file_path = os.path.join(path, file)
            total_size += os.path.getsize(file_path)
    return total_size

def write_to_log_file(message):
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"{timestamp} - {message}\n"
    with open(LOG_FILE, 'a') as file:
        file.write(log_entry)

def purge_old_files():
    now = time.time()
    cutoff = now - (DAYS_OLD * 86400)
    
    for path, _, files in os.walk(TEMP_FOLDER):
        for file in files:
            file_path = os.path.join(path, file)
            if os.path.getmtime(file_path) < cutoff:
                os.remove(file_path)
                write_to_log_file(f"Deleted {file_path}")

def check_and_purge_folder():
    folder_size_before = get_folder_size()
    write_to_log_file(f"Size before purge: {folder_size_before} bytes")
    
    purge_old_files()
    
    folder_size_after = get_folder_size()
    write_to_log_file(f"Size after purge: {folder_size_after} bytes")

# Schedule the folder check and purge to run daily at midnight
schedule.every().day.at("00:00").do(check_and_purge_folder)

while True:
    schedule.run_pending()
    time.sleep(1)

Output

Code Details

Get National Weather Service Forecast

Code

import requests

def get_weather_forecast():
    url = "https://api.weather.gov/gridpoints/SLC/100,175/forecast"
    headers = {
        'User-Agent': 'Weather application',
        'Accept': 'application/json',
    }
    graph_line = ""
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        forecast_data = response.json()
        print()
        print("Salt Lake City Weather Forecast")
        print("-" * 130)
        print("Period".ljust(17) + "Temp".ljust(8) + "Graph".ljust(70) + "Forecast")
        print("-" * 130)
        for period in forecast_data['properties']['periods'][:11]:  # Adjust slice to change periods
            graph_line = "\u2584" * period['temperature']
            print(f"{period['name'].ljust(17)}{period['temperature']}°{period['temperatureUnit'].ljust(5)}{graph_line.ljust(70)}{period['shortForecast']}")
        print("-" * 130)
        print()
    else:
        print("Failed to retrieve forecast data")

if __name__ == "__main__":
    get_weather_forecast()

Output

----------------------------------------------------------------------------------------------------------------------------------
Salt Lake City Weather Forecast
----------------------------------------------------------------------------------------------------------------------------------
Period           Temp    Graph                                                                 Forecast
----------------------------------------------------------------------------------------------------------------------------------
This Afternoon   57°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄             Mostly Sunny
Tonight          45°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                         Mostly Cloudy
Friday           59°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄           Chance Light Rain
Friday Night     42°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                            Chance Light Rain
Saturday         53°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                 Rain then Patchy Blowing Dust
Saturday Night   28°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                                          Snow
Sunday           38°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                                Snow Likely
Sunday Night     21°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                                                 Chance Light Snow
Monday           38°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                                Slight Chance Light Snow
Monday Night     21°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                                                 Mostly Cloudy
Tuesday          41°F    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄                             Mostly Sunny
----------------------------------------------------------------------------------------------------------------------------------

Code Details



 





© 2023 John Gordon
Cascade Street Publishing, LLC