Env file.
This commit is contained in:
parent
149659064d
commit
2808952153
@ -1 +1,68 @@
|
||||
"""
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 retoor
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
Author: retoor <retoor@molodetz.nl>
|
||||
Description: Utility to load environment variables from a .env file.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
def load_env(file_path: str = '.env') -> None:
|
||||
"""
|
||||
Loads environment variables from a specified file into the current process environment.
|
||||
|
||||
Args:
|
||||
file_path (str): Path to the environment file. Defaults to '.env'.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the specified file does not exist.
|
||||
IOError: If an I/O error occurs during file reading.
|
||||
"""
|
||||
try:
|
||||
with open(file_path, 'r') as env_file:
|
||||
for line in env_file:
|
||||
line = line.strip()
|
||||
# Skip empty lines and comments
|
||||
if not line or line.startswith('#'):
|
||||
continue
|
||||
# Skip lines without '='
|
||||
if '=' not in line:
|
||||
continue
|
||||
# Split into key and value at the first '='
|
||||
key, value = line.split('=', 1)
|
||||
# Set environment variable
|
||||
os.environ[key.strip()] = value.strip()
|
||||
except FileNotFoundError:
|
||||
raise FileNotFoundError(f"Environment file '{file_path}' not found.")
|
||||
except IOError as e:
|
||||
raise IOError(f"Error reading environment file '{file_path}': {e}")
|
||||
|
||||
|
||||
try:
|
||||
load_env()
|
||||
except Exception as e:
|
||||
pass
|
||||
|
Loading…
Reference in New Issue
Block a user