.env 文件解析器
解析 .env 文件并将变量显示为表格或转换为 JSON。
常见问题
代码实现
def parse_env(text: str) -> dict:
result = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
eq = line.find("=")
if eq == -1:
continue
key = line[:eq].strip()
value = line[eq+1:].strip()
# Strip surrounding quotes
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
value = value[1:-1]
result[key] = value
return result
env_text = """
DB_HOST=localhost
DB_PORT=5432
API_KEY="s3cr3t"
"""
import json; print(json.dumps(parse_env(env_text), indent=2))Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.