加载 .env 文件(可执行文件同目录或项目根目录)
()
| 29 | |
| 30 | |
| 31 | def _load_dotenv(): |
| 32 | """加载 .env 文件(可执行文件同目录或项目根目录)""" |
| 33 | env_path = project_root / ".env" |
| 34 | if not env_path.exists(): |
| 35 | return |
| 36 | with open(env_path, encoding="utf-8") as f: |
| 37 | for line in f: |
| 38 | line = line.strip() |
| 39 | if not line or line.startswith("#") or "=" not in line: |
| 40 | continue |
| 41 | key, _, value = line.partition("=") |
| 42 | key = key.strip() |
| 43 | value = value.strip().strip('"').strip("'") |
| 44 | if key and key not in os.environ: |
| 45 | os.environ[key] = value |
| 46 | |
| 47 | |
| 48 | def _can_bind_port(host: str, port: int) -> bool: |