我的.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
答案 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
值。