使用参数替换将bash环境变量集读取到Python变量中

时间:2019-03-27 15:47:57

标签: python bash environment-variables substitution dotenv

我的.env文件中有以下环境变量:

DT="2019-01-01"
X=${DT//-/}

变量X是使用Bash的参数替换设置的,并使用${parameter//pattern/string}格式替换了所有出现的内容(文档here)。

现在,要将环境变量读入Python,我在文件Config中创建了Python类config.py

from dotenv import find_dotenv, load_dotenv
import os

class Config:
    def __init__(self):
        load_dotenv(find_dotenv())

        self.X = os.environ.get('X')

python外壳中,我运行:

In [1]: from config import Config

In [2]: c = Config()

In [3]: c.X
Out[3]: ''

这里c.X是一个空字符串'',在这里我希望它是'20190101'

如何将环境变量的正确值加载到python变量中?

编辑:当我在bash脚本中键入echo $X时,它将打印正确的值。例如,bash脚本sample.sh

#!/bin/bash
source .env

echo $X

运行时,我得到:

$ sh sample.sh
20190101

2 个答案:

答案 0 :(得分:0)

Dotenv不使用Bash;它在内部解析文件。参见dotenv GitHub page

直接使用DT代替:

self.X = os.environ.get('DT').replace('-', '')

答案 1 :(得分:0)

我通过以下方式在export文件中添加了.env

DT="2019-01-01"
export X=${DT//-/}

这使我能够在Python中获得正确的c.X值。