Debian Codegraph @

scripts/run_with_env.py

raw
1 # Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
2
3 """Run a command with environment variables loaded from a .env file."""
4
5 from __future__ import annotations
6
7 import os
8 import subprocess
9 import sys
10 from pathlib import Path
11
12
13 def load_env_file(env_path: str | None = None) -> None:
14 """Load environment variables from a .env file."""
15 if env_path is None:
16 # Get ".eenv" file from the current directory
17 env_path = Path.cwd() / ".env"
18 if not Path(env_path).is_file():
19 raise FileNotFoundError(f"Environment file not found: {env_path}")
20 print(f"Loading environment variables from: {env_path}")
21 with open(env_path, encoding="utf-8") as f:
22 for line in f:
23 line = line.strip()
24 if not line or line.startswith("#") or "=" not in line:
25 continue
26 key, value = line.split("=", 1)
27 os.environ[key.strip()] = value.strip()
28 print(f" Loaded variable: {key.strip()}={value.strip()}")
29
30
31 def execute_command(command: list[str]) -> int:
32 """Execute a command with the loaded environment variables."""
33 print("Executing command:")
34 print(" ".join(command))
35 print("")
36 result = subprocess.call(command)
37 print(f"Process exited with code {result}")
38 return result
39
40
41 def main() -> None:
42 """Main function to load environment variables and execute a command."""
43 if len(sys.argv) < 2:
44 print("Usage: python run_with_env.py <command> [args ...]")
45 sys.exit(1)
46 print("🏃 Running with environment variables")
47 load_env_file()
48 return execute_command(sys.argv[1:])
49
50
51 if __name__ == "__main__":
52 main()