python - 如何在 Python 程序中读取(仅读取未设置).env 文件
问题描述
我有.env
以下内容的文件:
DB_URL=''
DB_USER=''
DB_PASSWD=''
DB_NAME=''
COLLECTION_NAME=''
问题我想.env
在我的 python 程序中读取这个文件来创建连接,mongodb
但我只找到python
了设置并使用模块env
读取的库。os
有没有办法只读取的内容.env
?
解决方案
为什么不直接打开文件并自己解析呢?
import pathlib
def read_env(directory):
env_path = pathlib.Path(directory) / '.env'
d = {}
with env_path.open('r') as f:
for line in f:
if '=' in line and not line.startswith('#'):
# 2nd check allows for files with commented lines, but if you
# want to have keys starting with a literal '#', just have the
# 1st part of the if.
key, value = line.split('=', 1)
d[key] = value.strip("'")
return d
推荐阅读
- wordpress - 如何确保简码结果不会破坏格式?
- excel - 将动态控件添加到 Excel VBA 用户窗体中的框架时出错
- scheme - 如何从字符列表中输出字符网格?
- android - 应用程序没有向用户显示任何可见的崩溃,但 android vitals 仍然给我 Firebase 的崩溃报告
- c++ - 为什么可以从类中的对象访问类的私有变量?
- python-3.x - 无法从 azure devops 安装 mcafee-epo
- javascript - 如何仅使用终端输出vscode打开JS文件时显示的问题列表:?
- command - 在某些情况下,命令是否应该“无所事事”
- reactjs - 环境变量只能在开发过程中访问,如何在部署网站后使其工作?(GatsbyJS 项目)
- java - 为什么类的泛型会影响方法的泛型