Stephen Gilmore

🐍 Small Python script template

Python August 29th, 2022 1 minute read.

I'm sort of tired of starting from scratch every time and always Googling log formats and the best way to read a file from the current directory. Here's a template for a super basic python script.

import logging
from pathlib import Path

logger = logging.getLogger(__name__)


def read_file(file_name: str) -> str:
    file_path = Path().cwd() / file_name

    with open(file_path, "r") as f:
        return f.read()


def main():
    logger.info("Starting main()")
    pass


if __name__ == "__main__":
    # Try to use the rich handler for logging first
    try:
        from rich.logging import RichHandler
        logging_handlers = [RichHandler()]
    # Use the built-in handler if rich isn't available
    except ModuleNotFoundError:
        logger.warning("Rich text package unavailable.")
        logging_handlers = [logging.StreamHandler()]

    # Configure the logger
    logging.basicConfig(
        format="%(name)s: %(message)s",
        datefmt="[%X]",
        level=logging.INFO,
        handlers=logging_handlers,
    )

    # Run the main() function
    main()

References: