Software Studio
Back to Articles

Python Automation: Scripts That Save Hours Every Week

PythonAutomationGCP
Cover illustration for Python Automation: Scripts That Save Hours Every Week

Python isn't my primary language for web development, but it's my first choice for automation. The standard library is extensive, the package ecosystem is unmatched for data processing, and the syntax optimizes for readability, which matters when you revisit a script six months later.

What's worth automating

The most valuable automation scripts solve recurring manual tasks. Every developer has them:

  • Downloading reports
  • Transforming data formats
  • Syncing information between systems
  • Cleaning up cloud resources

If you do something manually more than three times, script it. The first time you're learning the task. The second time you're confirming it repeats. By the third, you know enough to write it down as code.

Data pipeline scripts

Data pipeline scripts are where Python excels. A typical pattern:

  1. Read data from a Google Sheet using gspread.
  2. Transform it with pandas.
  3. Validate it with custom rules.
  4. Load it into BigQuery.
import gspread
import pandas as pd

sheet = gspread.service_account().open("Weekly Sales").sheet1
df = pd.DataFrame(sheet.get_all_records())

df["order_date"] = pd.to_datetime(df["order_date"])
df = df[df["amount"] > 0]

df.to_gbq("reporting.weekly_sales", if_exists="replace")

What takes an analyst two hours of manual work runs in thirty seconds as a scheduled Cloud Function. It also runs the same way every time, which a tired person on a Friday afternoon does not.

Infrastructure automation beyond Terraform

Infrastructure automation goes beyond Terraform. Terraform describes what should exist. Python scripts handle the operational tasks around it:

  • Rotating secrets across services.
  • Auditing IAM permissions.
  • Cleaning up old Docker images in Artifact Registry.
  • Generating cost reports from billing data.

These scripts run as scheduled Cloud Run jobs or Cloud Functions. For the declarative side, see Terraform at Scale.

API integrations

API integrations are bread and butter.

  • Pull data from Slack and push it to a spreadsheet.
  • Sync Jira tickets with a custom dashboard.
  • Monitor third-party service status and alert on degradation.

The requests library and each service's Python SDK make these integrations straightforward. Most of the work is deciding what should happen when the other service is slow or returns something unexpected.

Turn scripts into tools with Click

Click, the CLI framework, transforms scripts into proper command-line tools. Add argument parsing, help text and subcommands in a few decorators.

import click


@click.command()
@click.option("--days", default=30, help="Delete images older than this many days.")
@click.option("--dry-run", is_flag=True, help="Show what would be deleted.")
def cleanup(days: int, dry_run: bool) -> None:
    """Remove old container images from Artifact Registry."""
    for image in find_stale_images(days):
        if dry_run:
            click.echo(f"Would delete {image}")
        else:
            delete_image(image)


if __name__ == "__main__":
    cleanup()

This matters when other team members need to use your tools. A script with --help is immediately more accessible than one that requires reading the source.

Error handling for scripts nobody is watching

Error handling in automation scripts needs special attention. Unlike web applications where a user sees an error page, a failed script might run at 3 AM with no one watching.

  • Log aggressively. The log is the only witness.
  • Send alerts on failure. A job that fails silently for three weeks is worse than no job.
  • Make scripts idempotent so they can be safely re-run after a partial failure.
  • Use try/except for expected failures such as API timeouts and rate limits, and let unexpected errors propagate.

Catching every exception and carrying on is the most common mistake. An unexpected error should stop the script loudly, so that someone finds out.

Testing automation scripts

Testing automation scripts is different from testing web applications. You're often interacting with external services and processing real data. I use a combination of:

  • Unit tests for transformation logic.
  • Integration tests with service emulators or sandbox environments.
  • Dry-run modes that execute the full pipeline but skip the final write step.

The dry run is the one I'd add first. Being able to see exactly what a script would do, before it does it, prevents most automation accidents.

How I organize and run them

The operational pattern:

  • Scripts live in a dedicated repository, each in its own directory with a README and requirements.txt.
  • A Makefile provides standard commands: make run, make test, make deploy.
  • Cloud Scheduler triggers the Cloud Function or Cloud Run job on the appropriate schedule.
  • Monitoring confirms each run succeeded.

The last point is easy to skip. Alerting on failure tells you when a script breaks. Checking that a run happened at all tells you when the schedule itself has quietly stopped.

Where to start

Pick the manual task you least enjoy and write the smallest script that removes it. Give it a --dry-run flag, log what it does, and put it on a schedule. Once one script has saved you an hour a week, finding the next candidate takes no effort at all.