Skip to content

Python Code Templates

These python code templates are based on software tools that I have developed lately. They can be a helpful reference for future projects.

Basic ArgParse Template

A python script which takes command line arguments using argparse and runs a main function

import argparse
import sys

def main(args_dict):
    # Print arguments
    print("Arguments:")
    for arg in args_dict.keys():
        print(f"  {arg} = {args_dict[arg]}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--input_file", type=str, help="Path to input file")
    args = parser.parse_args()

    print("Starting...")

    args_dict = vars(args) # Make args into a dictionary
    main(args_dict) 

    print("Done!")

    sys.exit(0)

Thread Class Template

A wrapper class around a thread object

from threading import Thread
from time import sleep


class ThreadClass(object):
    def __init__(self, name):
        self.name = name
        self.thread = None
        self.run_thread = False

    def __str__(self):
        return self.name
    
    def start(self, thread_msg="Thread running.."):
        self.thread = Thread(target=self.run, args=(thread_msg,))
        self.thread.start()

    def stop(self):
        self.run_thread = False

    def run(self, thread_msg):
        self.run_thread = True
        while self.run_thread:
            print(f"[{self.name}]: {thread_msg}")
            sleep(1)

        print("Exiting thread")


if __name__ == "__main__":
    print("Starting...")
    thread_obj = ThreadClass("test")

    print("Starting thread...")
    thread_obj.start("Custom thread update message...")
    sleep(4)

    print("Stopping thread...")
    thread_obj.stop()

    print("Exiting...")

CLI Thread Class Template

Builds upon the thread class template to have a background task listening for user input

from threading import Thread
from time import sleep


class CliThreadClass(object):
    def __init__(self, name):
        self.name = name
        self.thread = None
        self.run_thread = False

    def __str__(self):
        return self.name
    
    def start(self, thread_msg="Thread running.."):
        self.thread = Thread(target=self.run, args=(thread_msg,))
        self.thread.start()

    def stop(self):
        self.run_thread = False

    def run(self, thread_msg):
        self.run_thread = True
        while self.run_thread:
            cmd = input("> ")

            if not cmd:
                continue

            if "exit" in cmd.split(" "):
                self.stop()
            else:
                print(f"  (You typed {len(cmd.split(' '))} words)")
                

        print("Exiting thread")



if __name__ == "__main__":
    print("Starting...")
    cli_obj = CliThreadClass("test")

    print("Starting thread...")
    cli_obj.start("Custom thread update message...")

    count = 0
    while cli_obj.run_thread:
        count += 1
        print(f" - Counted {count} sheep...")
        sleep(2)

    print("Exiting...")

MatplotLib Template

A script that serves as a starting point for data plotting script with matplotlib

from matplotlib import pyplot as plt

def plot(x_data, y_data, title="Title"):
    plt.plot(x_data, y_data, linestyle="-", marker=".", color="green", label="Some Data")
    plt.xlabel("X Data")
    plt.ylabel("Y Data")
    plt.title(title)
    plt.grid(True)
    plt.legend(loc="upper right")
    plt.show()

if __name__ == "__main__":
    N = 100
    X = [x for x in range(N)]
    Y = [abs(x - 50) for x in X]

    print(f"Plotting {N} points")
    plot(X, Y)

Leave a Reply

Your email address will not be published. Required fields are marked *