Hello ! I'm discovering the use of environment variables through an .env file (!= of a venv) with Python and I'd like to have a critique for two distinct situations for its use.
โก๏ธ Context: I have a project with the following file structure:
โโโ annots1
โย ย โโโ annot.csv
โโโ annots2
โย ย โโโ annot.csv
โโโ folder2
โย ย โโโ deep
โย ย โย ย โโโ deeper
โย ย โย ย โโโ deepest
โย ย โย ย โโโ deep_script.py
โย ย โโโ question1.py
โย ย โโโ question2.py
โโโ utils
โโโ upper_script.py
โก๏ธ I've installed the python-dotenv module, which allows me to load an .env into the project (it looks for an .env file in the folders above it).
โก๏ธ Here are the contents of my .env file:
PROJECT_PATH=/TEST
ANNOT2_PATH=/TEST/annots2/annot.csv
UPPER_SCRIPT_PATH=/TEST/utils/upper_script.py
UPPER_SCRIPT_NAME=upper_script
๐ First situation: Loading a file as a resource:
import os
from pathlib import Path
from dotenv import load_dotenv
import pandas as pd
def get_annots(file_path_name:str):
return pd.read_csv(file_path_name)
def main():
annot_file_path_name = Path(os.getenv('PROJECT_PATH')) / "annots1" / "annot.csv"
get_annots(annot_file_path_name)
annot2_file_path_name = Path(os.getenv('ANNOT2_PATH'))
get_annots(annot2_file_path_name)
if __name__ == "__main__":
load_dotenv()
main()
The advantage is that if I use this same code from another python file, for example the deep_script.py file, it still works!
๐ Second situation:
I want to use a function from a utility python file in a folder parallel to my launch script. I don't think there's an easy way to retrieve this function. The same problem exists with a python file higher in the file hierarchy. It seems to me that I should be able to use sys.path(...).
In the question2.py script I have the following code: (not enough chars...)