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

问题描述 投票:1回答:2

我的.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 shell中,我运行:

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
python bash environment-variables substitution dotenv
2个回答
0
投票

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

直接使用DT代替:

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

0
投票

我以这种方式在我的export文件中添加了一个.env

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

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

© www.soinside.com 2019 - 2024. All rights reserved.