-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrun_with_env.py
More file actions
79 lines (65 loc) · 2.91 KB
/
run_with_env.py
File metadata and controls
79 lines (65 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
"""Run a command with environment variables loaded from a .env file."""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
def load_env_file(env_path: str | None = None) -> None:
"""Load environment variables from a .env file."""
# Set a flag to indicate that the environment has been loaded by this script
# This prevents batch scripts (like utils.bat) from reloading .env and overwriting variables
if env_path is None:
# Get ".env" file from the current directory
env_path = Path.cwd() / ".env"
if not Path(env_path).is_file():
raise FileNotFoundError(f"Environment file not found: {env_path}")
print(f"Loading environment variables from: {env_path}")
with open(env_path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
value = os.path.expandvars(value.strip())
# Handle PATH variable specifically:
# 1. Convert relative paths to absolute paths
# 2. Normalize path separators
if key.strip().upper() == "PATH":
paths = value.split(os.pathsep)
abs_paths = []
for p in paths:
p = p.strip()
if not p:
continue
# Check if it looks like a relative path component
# (not starting with drive or root)
# Note: This simple check assumes standard usage in .env
if not os.path.isabs(p) and not p.startswith("%"):
try:
# Resolve relative to .env file directory
p = str((Path(env_path).parent / p).resolve())
except Exception:
pass # Keep as is if resolution fails
abs_paths.append(os.path.normpath(p))
value = os.pathsep.join(abs_paths)
os.environ[key.strip()] = value
print(f" Loaded variable: {key.strip()}={value}")
def execute_command(command: list[str]) -> int:
"""Execute a command with the loaded environment variables."""
print("Executing command:")
print(" ".join(command))
print("")
result = subprocess.call(command)
print(f"Process exited with code {result}")
return result
def main() -> None:
"""Main function to load environment variables and execute a command."""
if len(sys.argv) < 2:
print("Usage: python run_with_env.py <command> [args ...]")
sys.exit(1)
print("🏃 Running with environment variables")
load_env_file()
return execute_command(sys.argv[1:])
if __name__ == "__main__":
main()