从环境文件中读取环境变量 [英] Reading in environment variables from an environment file

查看:318
本文介绍了从环境文件中读取环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在本地环境中运行Python脚本,该脚本通常在Docker容器中运行。 docker-compose.yml 指定一个 env_file (部分看起来)如下:

I'd like to run in a local environment a Python script which is normally run in a Docker container. The docker-compose.yml specifies an env_file which looks (partially) like the following:

DB_ADDR=rethinkdb
DB_PORT=28015
DB_NAME=ipercron

为了在本地运行此命令,我希望将这些行转换为

In order to run this locally, I would like these lines to be converted to

os.environ['DB_ADDR'] = 'rethinkdb'
os.environ['DB_PORT'] = '28015'
os.environ['DB_NAME'] = 'ipercron'

我可以写我的解析器,但是我想知道是否有任何现有的模块/工具可以从配置文件中读取环境变量?

I could write my parser, but I was wondering if there are any existing modules/tools to read in environment variables from configuration files?

推荐答案

Python Dotenv库。只需安装库 pip install python-dotenv ,使用环境变量创建 .env 文件,然后导入环境像这样的代码中的变量:

I use Python Dotenv Library. Just install the library pip install python-dotenv, create a .env file with your environment variables, and import the environment variables in your code like this:

import os
from dotenv import load_dotenv

load_dotenv()

MY_ENV_VAR = os.getenv('MY_ENV_VAR')

.env 文件:

MY_ENV_VAR="This is my env var content."

当我需要在docker系统之外测试代码并准备将其再次返回docker时,这就是我要做的事情

This is the way I do when I need to test code outside my docker system and prepare it to return it into docker again.

这篇关于从环境文件中读取环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆