This script is used to enable importing local Python modules from your project directory without having to install the project in development mode or modify PYTHONPATH
environment variable manually every time. The .pth
file, is a special file that Python looks for when determining import paths.
Note that you need to be in your local
module
dir, then run these commands.
CURRENT_FOLDER=$(pwd) && echo "$CURRENT_FOLDER"
Then we find the .env
path:
$(poetry env info -p)
will return the virtual environment path (created by Poetry)- Use globbing (
python*
) withls -d
to find the Python version directory - To finally, constructs a path to a file called
project_dir.pth
SITE_PACKAGES_FOLDER="$(ls -d $(poetry env info -p)/lib/python*/site-packages/)project_dir.pth" && echo "$SITE_PACKAGES_FOLDER"
Or, if Poetry is not used, you must first cd
into the .env
directory, then run:
ENV_PATH="$(pwd -L)"
SITE_PACKAGES_FOLDER="$(ls -d $ENV_PATH/lib/python*/site-packages/)project_dir.pth" && echo "$SITE_PACKAGES_FOLDER"
Finally, we append
echo "$CURRENT_FOLDER" >> "$SITE_PACKAGES_FOLDER"
Original Source: StackOverFlow.com
This method allows you to directly reference your project directory in your scripts without creating a .pth
file.
Insert this at the beginning of your Python scripts:
import sys
import os
from pathlib import Path
# Get the absolute path of the module directory. Must change to match your use case.
module_dir = Path().resolve() / "module_dir"
# Add the project root to Python's path
sys.path.append(module_dir)
# Now you can import your local modules
import your_module