It is my surrender to writing down notes relating to my coursework. Somehow I am caught by the obsession that only about 35 G disk space is left on my server, leading to more compact posts, and that sucks.

Nevertheless, it should be meaningful and I believe it would be constructive to my study.

Makefile is a plaintext file that helps you build an environment to run programs(codes). For example, if you want to have your local code to be tested on your friend's computer, what should you do? Grab his computer and pip install all packages? It's not portable at all, so Makefile, or just makefile, come to help.

In my case, I have to run the code on a Linux server.

  • all: what to run when you only type 'make' in the terminal
  • build: install all dependencies and create the env, feel free to use the word you like
  • run: what code to execute
  • clean: remove the cache
  • .PHONY: make sure that the filename is not misused with files having the same names
# Variables
VENV_DIR = venv
PYTHON = $(VENV_DIR)/bin/python
PIP = $(VENV_DIR)/bin/pip

# Default target
all: build

# Install Python and virtual environment dependencies
build:
# substitute user do
# Sudo stands for either "substitute user do" or "super user do" and it allows you to temporarily
# elevate your current user account to have root privileges. This is different from “su” which is not temporary.

    sudo apt update
    # The -y flag automatically confirms any prompts during the installation process.
    sudo apt install -y python3-pip python3-venv
    # Create a virtual environment if it is not existed
#     The -m option is used with the Python interpreter to run a module as a script. When you use python -m module_name,
#     Python executes the module specified by module_name as if it were a script, allowing you to use modules that provide command-line interfaces.
    
    test -d $(VENV_DIR) || $(PYTHON) -m venv $(VENV_DIR)
    $(PIP) install -r requirements.txt

# Run the program
run:
    $(PYTHON) warmup.py $(file)

# Clean up the environment
clean:
    rm -rf $(VENV_DIR)
    find . -type f -name "*.pyc" -delete
    find . -type d -name "__pycache__" -delete

# Phony targets declaration
.PHONY: build run all clean

makefile.png
makefile.png

For detailed and formal tutorial, please check:
https://earthly.dev/blog/python-makefile/
https://medium.com/aigent/makefiles-for-python-and-beyond-5cf28349bf05